如何在for循环中运行一个项目的函数,然后再转到下一个项目?

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等

我试图做的是循环通过电子邮件条目中的每封电子邮件,并运行该电子邮件的检查来validation它。 但是,我注意到,它会循环到validation模块(client.single.check)完成之前的下一个项目,因此将在我的数据库path中推错了“x”(项目)。 如果它在第0项上,它会在我有“x”的数据库path中推到x = 1。

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

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

这是因为你在这里有asynchronous代码。 考虑用recursion函数replace你的循环,如:

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