简体   繁体   English

在for循环中顺序执行promise

[英]Sequentially executing promises inside a for loop

I am straggling with chaining two promises inside a loop, so that promise number two, does not start until promise one has been resolved. 我在循环中链接两个承诺,所以承诺二号,直到承诺一解决后才开始。

I saw an example with reduce. 我看到了一个减少的例子。 Could not get it to work, yet. 无法让它发挥作用。 If I just do then, as I currently have, the code executes in parallel - as in, all async requests are fired off, and of course the results are messed-up. 如果我就这样做,就像我现在所做的那样,代码并行执行 - 就像在所有异步请求被触发一样,当然结果搞砸了。 Please take a look: 请看一下:

for ( var i = 0; i < dummyData.accounts.length; i++) {
  var cursorUser = dummyData.accounts[i];
  var auth0User = {
    email: cursorUser.email,
    password: 'abc123',
    connection: 'Username-Password-Authentication'
  };
  createUser(api, auth0User)
    .then(function (auth0Info) {
      return auth0Info;
    })
    .then(function(auth0Info) {
      cursorUser.authProfile = auth0Info;
      console.log("account: ", cursorUser);
      return create(accountsAPIService, cursorUser);
    })
}

Simply avoid for loops for asynchronous work. 简单地避免for异步工作循环。

Arrays have functional methods like forEach and map for this kind of thing. 数组有像forEach这样的函数方法和map这样的东西。

var pendingResults = dummyData.accounts.map(function (account) {
    return createUser(api, {
        email: account.email,
        password: 'abc123',
        connection: 'Username-Password-Authentication'
    }).then(function (authInfo) {
        console.log("account: ", authInfo);
        return create(accountsAPIService, authInfo);
    });
});

Promise.all(pendingResults).then(function (results) {
    // everything is done
});

See @Tomalak's answer for the actual solution. 请参阅@ Tomalak对实际解决方案的回答


The problem is that a for clause does not create a new scope for the variables. 问题是for子句不会为变量创建新的范围。 In other words, you code is understood as: 换句话说,您的代码被理解为:

var i, cursorUser, auth0User;
for (i = 0; i < dummyData.accounts.length; i++) {
  cursorUser = dummyData.accounts[i];
  auth0User = {
    // ...
  };
  // ...
}

When the async promise is resolved, another iteration probably has already overwritten the cursorUser variable: the then callback cannot read the value of the iteration that started its promise anymore. 当async promise被解析时,另一个迭代可能已经覆盖了cursorUser变量: then callback不能再读取启动其promise的迭代值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM