gpt4 book ai didi

javascript - 来自 promise.each 的未处理拒绝

转载 作者:行者123 更新时间:2023-11-29 21:00:56 25 4
gpt4 key购买 nike

我正在尝试使用 bluebird 的 Promise.each() 进行多个数据库查询。我被卡住的部分是我无法处理所有拒绝(如果多个 promise 失败)。如果我使用 Promise.all() 做同样的事情,它工作正常(它会!因为在 Promise.all() 中,如果 1 个 promise 失败,结果也会被拒绝)。我的问题是:我应该如何处理 Promise.each() 中的拒绝?

function foo(bar){
return new Promise(resolve, reject){
var query = "elect count(*) from students Where 1=1";//DELIBRATE MISTAKE
connection.query(query, function(err, result){
if(err){reject(err)}resolve(result);
})
}
}
function api(req, res){
var tasks = [];
for(var i = 0; i < 10; i++){
tasks.push(foo(bar));
}
Promise.each(tasks).catch(err=>{return err;});
res.send('message')
}

回应:未处理的拒绝错误:ER_PARSE_ERROR

最佳答案

您错误地使用了 Bluebird#each 方法。此方法执行以下操作:

Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (value, index, length) where value is the resolved value of a respective promise in the input array.

所以第一个参数必须是一个 promise /值数组,第二个是一个回调,它接受三个参数:value, index, length

工作示例:

let queryAsync = Promise.promisify(connection.query, { context: connection });

function foo(bar) {
var query = 'elect count(*) from students Where 1=1'; // DELIBRATE MISTAKE
return queryAsync(query);
}

function api(req, res){
var tasks = [/* TODO: fill array with taskIds or something else*/];

Promise
.each(tasks, task => foo(task))
.then(() => res.send('message'))
.catch(err => {
console.log(err);
res.status(500).send(err);
});
}

在上面的示例中,我使用 Bluebird#promisify 方法来 promisify 回调式 connection.query 函数。 Bluebird 已经提供了 promisification 功能,您不应该创建自己的功能。

关于javascript - 来自 promise.each 的未处理拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46532382/

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