等待来自for循环的promises

时间:2015-08-18 20:05:46

标签: javascript asynchronous bluebird

以下代码并没有真正做到我想要的。

function doIt () {
  return new Promise (function (resolve, reject) {
    var promises = [];
    db.transaction(function(tx1){
      tx1.executeSql(function(tx2, rs) {
        for (var i = i; i < N; i++) {
          promises.push(db.transaction(function(tx3){
            ...
          }));
        }
      });
    });
    Promise.all(promises).then(resolve);
  });
}

现在它不起作用,因为Promise.all()在所有promises都在数组之前被执行,至少我认为这是正确的。

是否有一种优雅的方式可以保证所有这些承诺在结束之前完成?

1 个答案:

答案 0 :(得分:0)

您可以移动到 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let postcells: postsTableViewCell = tableView.dequeueReusableCellWithIdentifier("PostCell", forIndexPath: indexPath) as! postsTableViewCell let Post:PFObject = self.PostData.objectAtIndex(indexPath.row) as! PFObject postcells.postTimetextView.text = Post.objectForKey("Content") as! String var dateFormatter:NSDateFormatter = NSDateFormatter() dateFormatter.dateStyle = NSDateFormatterStyle.NoStyle dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle postcells.timeStamp.text = dateFormatter.stringFromDate(Post.createdAt!) var findPostedBy:PFQuery = PFUser.query()! findPostedBy.whereKey("objectId", equalTo: Post.objectForKey("Postedby")!) findPostedBy.findObjectsInBackgroundWithBlock{ (objects, error) -> Void in if error == nil { let USER:PFUser = (objects as NSArray).lastObject as! PFUser postcells.usernameLabel3.text = USER.username } } return postcells } 所在的位置,以便在Promise.all()循环完成填充数组后它正确:

for

仅供参考,混合承诺和回调可能会令人困惑,并且使得一致的错误处理变得特别困难。 function doIt () { return new Promise (function (resolve, reject) { var promises = []; db.transaction(function(tx1){ tx1.executeSql(function(tx2, rs) { for (var i = i; i < N; i++) { promises.push(db.transaction(function(tx3){ ... })); } Promise.all(promises).then(resolve); }); }); }); } 已经回复了承诺吗?如果是这样,你可以使用已经由数据库函数创建的promises来做更清洁的事情:

tx1.executeSql()

这会将function doIt() { return db.transaction.then(function(tx1) { return tx1.executeSql().then(function(tx2, rs) { var promises = []; for (var i = i; i < N; i++) { promises.push(db.transaction().then(function(tx3) { ... })); } return Promise.all(promises).then(resolve); }); }); } 处理程序的承诺返回到自动链接承诺。

相关问题