gpt4 book ai didi

javascript - 在 for 中同步进行异步调用

转载 作者:搜寻专家 更新时间:2023-11-01 00:42:41 26 4
gpt4 key购买 nike

我在处理 sails.js 中的异步事件时遇到了一些问题。

我正在从 JSONapi 获取一些数据,并尝试在 for 循环内将它们写入我的数据库。一切都需要一个接一个地执行(以正确的顺序)。为了使示例简单,我们只说我正在尝试执行以下操作:

//let apiNames be a JSON that contains some names in that order: James, Betty, Jon
//let Customer be a DB which contains that names and related age

for(index in apiNames){
console.log("Searching for "+apiNames[index].name+" in the Database...);
Customer.find({name:apiNames[index].name}).exec(function(err,customerData){
console.log("Found "+apiNames[index].name+" in the Database!");
console.log(customerData);
});
}

建议日志应该是这样的:

Searching for James in the Database....
Found James in Database!
{name:James, age:23}

Searching for Betty in the Database....
Found Betty in Database!
{name:Betty, age:43}

Searching for Jon in the Database....
Found Jon in Database!
{name:Jon, age:36}

由于 Javascript 异步运行并且数据库调用耗时很长,因此输出看起来像这样:

Searching for James in the Database....
Searching for Betty in the Database....
Searching for Jon in the Database....
Found James in Database!
{name:James, age:23}
Found Betty in Database!
{name:Betty, age:43}
Found Jon in Database!
{name:Jon, age:36}

我已经尝试了几种方法来强制循环同步工作,但没有任何效果。 AFAIK 如果我在 exec 中调用某些东西,它应该同步运行(通过将它与另一个 exec 链接),但我的问题是,它已经在循环中同步工作失败。有没有人对此有解决方案并可以解释一下?

编辑:apiNames 不是一个数组,它是一个包含一些数据的 JSON。以下是 apiNames 的示例:

[{
"name": "James",
"gender": "male"
},
{
"name": "Betty",
"gender": "female"
},
{
"name": "Jon",
"gender": "male"
}]

(添加性别以在 json 中包含更多信息。它对解决方案不重要)

最佳答案

由于 apiNames 是一个对象,为了与 IE9+ 兼容,我们可以使用 Object.keys() 来获取对象中的键名称并使用它来迭代 apiNames

//process all names in the array one by one
function process(apiNames, keys) {
//if there are no items in the array return from the function
if (!keys.length) {
return;
}
//get the first name in the array
var key = keys.shift();
var name = apiNames[key];
console.log("Searching for " + name + " in the Database...");
Customer.find({
name: name
}).exec(function (err, customerData) {
console.log("Found " + name + " in the Database!");
console.log(customerData);
//once the current item is processed call the next process method so that the second item can be processed
process(apiNames, keys);
});
}

//call the process method with an array
var keys = Object.keys(apiNames);
process(apiNames, keys);

对于旧版浏览器,使用 polyfill 添加对 Object.keys() 的支持,例如 one provided by MDN

演示:Fiddle

关于javascript - 在 for 中同步进行异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29245552/

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