[英]problems with Promises (nodejs, bluebird): process exits wihtout waiting for childs to be finished
我是Promises的新手,我肯定寫的代碼不正確(我尚不了解Promises的工作方式)。
從下面的代碼中,我希望該process.exit(0);
僅在其他所有操作完成時才執行。
但是在“ console.log( step 2
)”下面的代碼中,從不執行(在控制台中看到),因為我認為process.exit(0)
在等待其他進程之前就已運行。 有什么建議如何重組我的代碼?
var wordsToProcess = ['e301', 'e260']; // array with many words (could be mora than 2)
var actions = wordsToProcess.map((str) => {
console.log('(1) step ');
ingredient_get(str)
.then((ingredient_id) => {
console.log('(2) step '); //!!!! never console.log
return ingredient_id; // never return ingredient_id
});
});
var results = Promise.all(actions);
results.then(ingredient_id => {
process.exit(0); // should somehow wait for all ingredient_ids to come
});
function ingredient_get(name) {
var q_ingredients = knex('ingredients')
.select('id').where('name', name)
.then(pick_id)
var q_synonyms = knex('synonyms')
.select('ingredient_id as id').where('name', name)
.then(pick_id)
return Promise.all([q_ingredients, q_synonyms])
.then(([id1, id2]) => {
return id1 || id2; // only one id would be true here
})
}
這只是一個小錯誤,幾乎是一個錯字:您在map
回調中缺少return
:
var actions = wordsToProcess.map((str) => {
console.log('(1) step ');
return ingredient_get(str)
// ^^^^^^------------------------------------ add this
.then((ingredient_id) => {
console.log('(2) step ');
return ingredient_id;
});
});
因此, actions
只是充滿了undefined
而不是承諾的內容,因此Promise.all
的承諾沒有什么可等待的。
如果刪除console.log
(或濫用逗號運算符,但不要這樣做),則可以使用簡潔箭頭:
var actions = wordsToProcess.map((str) =>
ingredient_get(str)
.then((ingredient_id) => {
console.log('(2) step ');
return ingredient_id;
})
);
(實際上,如果您從一個簡潔的箭頭開始,然后返回並添加了日志記錄行,並將其轉換為冗長的箭頭,卻忘了添加return
,那我就不會感到驚訝。這是一個常見錯誤。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.