【问题标题】:jascript angular for loop executed after the promises承诺后执行的javascript angular for循环
【发布时间】:2016-12-02 18:18:54
【问题描述】:

我对 Promise 和 for 循环有疑问。以下代码不按顺序执行:

secondQuery.find().then(function(results) {
            alert("2") 
            for (var i in results) {
                (function(index){
                    var object = results[index];
                    var item_id = results[index].id;
                    var status = object.get("status");
                    var event_id = object.get("event_id");
                    var user_id = object.get("user_id");
                    var user_id_name = object.get("user_id_name");


                    var thumbimageurl = "";
                    var nFacebookFriends = 0;
                    var nInstagramFollowers = 0;
                    var nTwitterFollowers = 0;  

                    var query2 = new Parse.Query(User)
                    query2.equalTo("username",user_id)
                    return query2.first({
                        success: function(object) {
                            alert("3")
                            var thumbfile = object.get("thumb");
                            thumbimageurl = thumbfile.url();
                            nFacebookFriends = object.get('nFacebookFriends');
                            nInstagramFollowers = object.get('nInstagramFollowers');
                            nTwitterFollowers = object.get('nTwitterFollowers'); 
                        }
                    }).then(function(){
                        alert("4")
                        requests.push({
                            'thumb': thumbimageurl,
                            'item_id':item_id,
                            'status':status,
                            'event_id':event_id,
                            'user_id':user_id,
                            'user_id_name':user_id_name,
                            'nFacebookFriends':nFacebookFriends,
                            'nInstagramFollowers':nInstagramFollowers,
                            'nTwitterFollowers':nTwitterFollowers
                        })
                    })
                })(i)
            }
        }).then(function(){
                    alert('end')
                        $scope.requests = requests;
                        $localStorage.requests = requests;
                      //  alert(JSON.stringify(requests))
        })

在“2”警报而​​不是“3”和“4”的循环之后,我直接得到了“结束”。有没有办法强制 for 循环在下一个承诺之前执行?

【问题讨论】:

    标签: javascript angularjs for-loop promise


    【解决方案1】:

    您需要了解异步调用是如何发生的。这里发生的是最外层的块(secondQuery.find().then...)被执行,当promise返回时,回调同步执行(循环的所有迭代触发不同的异步调用),然后退出,执行then包含alert('end') 的块;因为在您的代码中,我观察到 query2.first 是一个异步调用,在调用 end 块之前不能返回。

    如果您希望end 块位于3 和4 之后,则必须将其链接到它们。这是保证您想要的顺序的唯一方法。或者您可以查找promise.all()(如果您的库使用bluebird)或promise.all() (es6)

    【讨论】:

      【解决方案2】:

      您可以创建一个 Promise 链,并且每个 Promise 都在链中的前一个 Promise 上挂起。因此,在 for 循环的每次迭代中,您都可以继续将 promises 添加到 promise chain。

      注意:但是我有一个问题@query2.first 这会返回一个承诺并且它还会回调?在那种情况下,我不知道回调部分会发生什么。

          secondQuery.find().then(function(results) {
          alert("2");
      
          // We will create a chain of promises here,
          // Each of it is pending on previouse promise in the chain
          var promise = Promise.resolve();
      
          for (var i in results) {
              (function(index) {                    
                  promise = promise.then(function() {                       
                      var object = results[index];
                      var item_id = results[index].id;
                      var status = object.get("status");
                      var event_id = object.get("event_id");
                      var user_id = object.get("user_id");
                      var user_id_name = object.get("user_id_name");
      
      
                      var thumbimageurl = "";
                      var nFacebookFriends = 0;
                      var nInstagramFollowers = 0;
                      var nTwitterFollowers = 0;  
      
                      var query2 = new Parse.Query(User);
                      query2.equalTo("username",user_id);
      
                      //I am not very sure about this,  this return a promise also there is a callback
                      //So When callback hits is out of this scope
                      return query2.first({
                          success: function(object) {
                              alert("3")
                              var thumbfile = object.get("thumb");
                              thumbimageurl = thumbfile.url();
                              nFacebookFriends = object.get('nFacebookFriends');
                              nInstagramFollowers = object.get('nInstagramFollowers');
                              nTwitterFollowers = object.get('nTwitterFollowers'); 
                          }
                      })
                  })
                  .then(function() {
                      alert("4");
                      requests.push({
                          'thumb': thumbimageurl,
                          'item_id':item_id,
                          'status':status,
                          'event_id':event_id,
                          'user_id':user_id,
                          'user_id_name':user_id_name,
                          'nFacebookFriends':nFacebookFriends,
                          'nInstagramFollowers':nInstagramFollowers,
                          'nTwitterFollowers':nTwitterFollowers
                      })
                  })
              })(i)
          }
      
          return promise;
      })
      .then(function(){
          alert('end');
          $scope.requests = requests;
          $localStorage.requests = requests;
          //  alert(JSON.stringify(requests))
      })
      

      【讨论】:

        猜你喜欢
        • 2015-12-18
        • 2017-12-30
        • 1970-01-01
        • 2016-10-11
        • 2015-05-05
        • 1970-01-01
        • 1970-01-01
        • 2015-11-27
        相关资源
        最近更新 更多