【发布时间】:2015-03-25 00:39:00
【问题描述】:
我在使用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 以异步方式运行并且 DB 调用需要很长时间,因此输出如下所示:
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一个数组 -
所以
apiNames是一个字符串? -
你能分享
apiNames的样本吗,结构......还有浏览器兼容性需要什么 -
我只是编辑了问题并分享了一个 apiNames 的示例。 JSON 要复杂得多。我只是缩短我的问题以保持示例清晰。
标签: javascript node.js asynchronous sails.js waterline