gpt4 book ai didi

javascript - 如何在嵌套 for 循环中链接 Promise?

转载 作者:行者123 更新时间:2023-12-01 02:32:55 25 4
gpt4 key购买 nike

var verifyEmail = function (thisEmail){
return new Promise(
function (resolve, reject) {
quickemailverification.verify(thisEmail, function (err, response) {
// Print response object
console.log(response.body);
if (response.body["success"] == "true"){
var validity = response.body["result"];
if (validity == "valid"){
console.log("Email Valid!");
resolve(validity);
} else {
console.log("Email Invalid!")
resolve(validity);
}
} else {
var reason = new Error("API unsuccessful");
reject(reason);
}
});
}
);
};

var saveValidity = function (validity){
return new Promise(
function (resolve, reject){
if (validity == "valid"){
var state = true;
admin.database().ref("/users_unverified/"+keys[i]+"/emails/"+x+"/verified/").set(state, function(error) {
if (error) {
console.log("Email ("+thisEmail+") verfication could not be saved" + error);
}
console.log("Email verification saved: " +thisEmail);
});
} else {
state = false;
admin.database().ref("/users_unverified/"+keys[i]+"/emails/"+x+"/verified/").set(state, function(error) {
if (error) {
console.log("Email ("+thisEmail+") verfication could not be saved" + error);
}
console.log("Email verification saved: " +thisEmail);
});
}
}
);
};

admin.database().ref("/users_unverified/").once('value').then(function(snapshot) {
var snap = snapshot.val();
keys = Object.keys(snap);

for (var i = 0; i < 100; i++){
var emails = snap[keys[i]]["emails"];
if (emails){
for (var x = 0; x<emails.length; x++){
var thisEmail = emails[x]["email"];
var emailVerified = emails[x]["verified"];
if (emailVerified != true || emailVerified != false){
verifyEmail
.then(saveValidity)
.then(function (fulfilled) {
console.log(fulfilled);
})
.catch(function (error){
console.log(error.message);
});
}
}
}
}
});

上面是我整理的代码。我不太相信它会起作用。我对 Promise 很陌生,所以我试图了解如何正确地做到这一点。

verifyEmail 函数应从代码第三 block 中的 firebase 查询中获取电子邮件地址。 saveValidity 函数应该接受来自 verifyEmail 的有效性响应。

但是,我还担心 firebase 查询 block 中的嵌套 for 循环。我正在循环访问每个用户以验证他们的电子邮件,但每个用户有时也有多个电子邮件。我担心它会在检查完前一个用户的所有电子邮件之前循环到下一个用户。

我也不确定是否可以像我一样将数据传递到 Promise 函数中。

这里肯定需要一些帮助。真的很努力地理解它是如何工作的。

最佳答案

首先,您需要修复 saveValidity() 以始终解析或拒绝 promise ,并传入其他变量 keythisEmail它引用:

const saveValidity = function (validity, key, thisEmail){
return new Promise(
function (resolve, reject){
if (validity == "valid"){
let state = true;
admin.database().ref("/users_unverified/"+key+"/emails/"+x+"/verified/").set(state, function(error) {
if (error) {
let msg = "Email ("+thisEmail+") verfication could not be saved" + error;
console.log(msg);
reject(new Error("Email ("+thisEmail+") verfication could not be saved" + error));
} else {
resolve("Email verification saved: " +thisEmail);
}
});
} else {
state = false;
admin.database().ref("/users_unverified/"+keys[i]+"/emails/"+x+"/verified/").set(state, function(error) {
if (error) {
let msg = "Email ("+thisEmail+") verfication could not be saved" + error;
console.log(msg);
reject(new Error(msg));
} else {
resolve("Email verification saved: " +thisEmail);
}
});
}
}
);
};

然后,对主循环进行一些更改:

  1. 我认为我们可以并行运行所有 verifyEmail() 调用,因为它们之间似乎没有任何关系。
  2. verifyEmail.then(...) 更改为 verifyEmail(thisEmail).then(...)` 以实际调用该函数
  3. 收集数组中的所有 verifyEmail() Promise
  4. 对 Promise 数组调用 Promise.all() 以监视它们何时全部完成
  5. .then() 返回值,以便我们在 Promise.all() 中获取返回值
  6. .catch() 中重新抛出,因此 Promise 保持被拒绝状态,并将过滤回 Promise.all()。如果您想忽略错误并继续处理其他错误,您可以在这里吃掉错误。
  7. var 切换到 let
  8. != 更改为 !==,因为它看起来像是您明确寻找 truefalse > 值并且不需要类型转换。
  9. 传入saveValidity()需要的变量。
  10. 比较emailVerified时更改逻辑,因为您之前的内容始终为真,因此可能不是正确的逻辑。我认为您想要知道 emailVerified 何时尚未设置为 truefalse 这意味着您必须使用 && ,而不是||
  11. 将外部 for 循环与 keys.length 进行比较,而不是硬编码值 100

并且,这是主嵌套 for 循环的结果代码:

admin.database().ref("/users_unverified/").once('value').then(function(snapshot) {
let snap = snapshot.val();
let keys = Object.keys(snap);

let promises = [];
for (let i = 0; i < keys.length; i++){
let key = keys[i];
let emails = snap[key]["emails"];
if (emails){
for (let x = 0; x < emails.length; x++) {
let currentKey = key;
let thisEmail = emails[x]["email"];
let emailVerified = emails[x]["verified"];
if (emailVerified !== true && emailVerified !== false){
promises.push(verifyEmail(thisEmail).then(validity => {
return saveValidity(validity, currentKey, thisEmail);
}).then(function (fulfilled) {
console.log(fulfilled);
return fulfilled; // after logging return value so it stays the resolved value
}).catch(function (error) {
console.log(error.message);
throw error; // rethrow so promise stays rejected
}));
}
}
}
}
return Promise.all(promises);
}).then(results => {
// all results done here
}).catch(err => {
// error here
});

关于javascript - 如何在嵌套 for 循环中链接 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48177757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com