gpt4 book ai didi

javascript - Promises 问题(nodejs、bluebird): process exits wihtout waiting for childs to be finished

转载 作者:行者123 更新时间:2023-12-01 02:30:29 25 4
gpt4 key购买 nike

我是 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 的引用,因此 Promise.all 的 Promise 无需等待对于。

如果您删除 console.log(或滥用逗号运算符,但是...不要),您可以使用简洁的箭头来代替:

var actions = wordsToProcess.map((str) =>
ingredient_get(str)
.then((ingredient_id) => {
console.log('(2) step ');
return ingredient_id;
})
);

(事实上,如果您开始使用简洁的箭头,然后返回并添加日志行并将其转换为详细的箭头,但忘记添加 return。这是一个常见的错误。)

关于javascript - Promises 问题(nodejs、bluebird): process exits wihtout waiting for childs to be finished,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48341872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com