【问题标题】:How to run a function for one item in a for loop before moving on to next item? [duplicate]如何在 for 循环中为一个项目运行一个函数,然后再继续下一个项目? [复制]
【发布时间】:2018-04-20 12:45:17
【问题描述】:
    for (var x = 0; x < emails.length; x++){
      var email = emails[x]["email"];
      client.single.check(email, true, true).then(
          result => {
            if (result.getNumericResult() == 0){
              console.log("valid email: "+email);
              var verified = 1;
              admin.database().ref("/users/"+userID+"/emails/"+x+"/verified").set(verified, function(error){
                if (error) {
                  console.log("User ("+userID+") email state could not be saved" + error);
                }
                console.log("Saved");
              });
            }
          },
          err => console.log('ERROR: ' + err.message)
      );
    }

上面是我的代码。

我有一个数据库条目“电子邮件”,它有多个电子邮件地址,分为:(0)-> 电子邮件:foo@bar.com,(1)-> 电子邮件:foo1@bar1.com 等。

我想要做的是遍历电子邮件条目中的每封电子邮件,并对该电子邮件进行检查以验证它。但是,我注意到它会在验证模块(client.single.check)完成之前循环到下一个项目,因此会在我的数据库路径中推送错误的“x”(项目)。如果它在第 0 项,它将推送到我有“x”的数据库路径中的 x=1。

我怎样才能使它对于 for 循环中的每个项目(电子邮件地址),它等待进行电子邮件检查并将结果推送到我的数据库,然后再转到 for 循环中的下一个项目?

所以坚持这个。对不起,新手的问题!

【问题讨论】:

  • for 循环的主体进行异步调用,因此从技术上讲,当前迭代在您收到所需数据之前完成。查看 Promise API 或 async

标签: javascript node.js callback promise


【解决方案1】:

这是因为您这里有异步代码。考虑用递归函数替换你的循环,比如:

function checkAnotherEmail() {
   // Your code
   result => {
       // Success code
       // Detection if there is a next email
       checkAnotherEmail();
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 2019-03-06
    • 2020-07-10
    相关资源
    最近更新 更多