[英]Node.js using async.forEach with async operation
具有一個函數,該函數需要遍歷數組,對每個項目執行異步操作,然后最終回調到調用方。
我可以得到async.forEach工作的基本案例。 當我這樣做時,它會起作用
async.forEach(documentDefinitions(), function (documentDefinition, callback) {
createdList.push(documentDefinition);
callback(); //tell the async iterator we're done
}, function (err) {
console.log('iterating done ' + createdList.length);
callback(createdList); //tell the calling method we're done, and return the created docs.
});
createdList的長度是正確的長度。
現在,我想每次通過循環執行另一個異步操作。 因此,我嘗試將代碼更改為以下內容;
function insert(link, callback){
var createList = [];
async.each(
documentDefinitions(),
function iterator(item, callback) {
create(collectionLink, item, function (err, created) {
console.log('created');
createdList.push(created);
callback();
});
},
function (err) {
console.log('iterating done ' + createdList.length);
callback(createdList);
}
);
}
其中create()是我的新異步操作。 現在我得到一個無休止的循環,我們似乎再也沒有碰到callback(createdList);
我嘗試將callback()移到異步create()方法的回調中,但是這些都不起作用。
請幫助我,我陷入了回調地獄!
將func更改為以下內容將其修復。
function insert(link, callback){
var createdList = [];
async.each(
documentDefinitions(),
function iterator(item, cb) {
create(collectionLink, item, function (err, created) {
console.log('created');
createdList.push(created);
cb();
});
},
function (err) {
console.log('iterating done ' + createdList.length);
callback(createdList);
}
);
}
不能確定,但是我認為這是將一次發生的回調更改為cb起到了作用。
這是一個范圍界定的問題,他們開始感到困惑了嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.