[英]Wait On For Loop In Node Promise
我正在嘗試使用Q庫運行一系列的Promise。
合並注釋功能會在數據庫中創建一個新注釋,由於某些獨特的限制,我必須按順序運行這些功能。
Promise按順序運行沒有問題,但是我需要將所有newNotes推送到workNotes中的數組中,然后解析該數組。
我嘗試過的一切都可以在鏈條結束之前解決諾言。
為了澄清這個問題,我需要在鏈完成並將每個結果newNote推送到notesList之后解決notesList。
workNotes(notes){
var _this = this;
var notesList = [];
return new Promise(
function(resolve,reject){
var chain = Q.when();
notes.forEach(function(note){
chain = chain.then(function(newNote){
_this.notesList.push(newNote);
return _this.mergeNotes(note);
});
});
resolve(notesList)
}
);
}
mergeNotes(notes){
return new Promise(
function(resolve,reject){
doSomething(note)
.then(function(newNote){
resolve(newNote);
})
}
);
}
更改mergeNotes()
以返回新的mergeNotes()
:
mergeNotes(notes){
return doSomething(note);
}
您正在返回一個諾言,但是它與doSomething()
諾言沒有任何聯系,因此它沒有等待。
避免使用將現有承諾包裝在新創建的承諾中的承諾反模式 。 相反,只需返回您已經擁有的承諾即可。
我將其余代碼更改為此:
workNotes(notes) {
let allNotes = [];
return notes.reduce(function(p, note) {
return p.then(function() {
return mergeNotes(note);
}).then(function(newNote) {
allNotes.push(newNote);
});
}, Promise.resolve()).then(function() {
return allNotes;
});
}
借助Bluebird Promise.mapSeries()
庫,您可以利用Promise.mapSeries()
來按順序處理數組並返回恰好需要的已解析數組:
workNotes(notes) {
return Promise.mapSeries(notes, function(note) {
return mergeNotes(note);
});
}
workNotes()
返回的workNotes()
的解析值將是一個注釋數組。
刪除無用的_this.
(請注意, this
與范圍無關!),避免使用Promise
構造函數antipattern ,交換對push
和mergeNotes
的調用順序,並使用reduce
代替forEach
將數組折疊為單個值:
function workNotes(notes) {
var notesList = [];
return notes.reduce(function(chain, note) {
return chain.then(function() {
return mergeNotes(note);
}).then(function(newNote){
notesList.push(newNote);
});
}, Q.when()).then(function() {
return notesList;
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.