我在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怎麼看起來像一個例子:(由性別有在JSON的一些詳細信息,它不重要的解決方案)
[{
"name": "James",
"gender": "male"
},
{
"name": "Betty",
"gender": "female"
},
{
"name": "Jon",
"gender": "male"
}]
是'apiNames'數組 – 2015-03-25 00:40:10
所以'apiNames'是一個字符串? – elclanrs 2015-03-25 00:44:24
你可以分享'apiNames'的樣本,結構...還需要什麼瀏覽器兼容性 – 2015-03-25 00:46:46