Javascript 我答应你
我对使用诺言表示怀疑。我需要有三个回调函数。所以我在Promise.all中写这三个函数,然后得到这三个函数的结果。这是一个正确的方法还是有其他方法?听起来你做得对,是的;如果您显示了代码,情况会更好 但假设您要启动三个进程,分别由doThis、doThat和doTheOther启动。你是这样处理的:Javascript 我答应你,javascript,node.js,promise,Javascript,Node.js,Promise,我对使用诺言表示怀疑。我需要有三个回调函数。所以我在Promise.all中写这三个函数,然后得到这三个函数的结果。这是一个正确的方法还是有其他方法?听起来你做得对,是的;如果您显示了代码,情况会更好 但假设您要启动三个进程,分别由doThis、doThat和doTheOther启动。你是这样处理的: Promise.all([ doThis(), doThat(), doTheOther() ]) .then(([thisResult, thatResult, theO
Promise.all([
doThis(),
doThat(),
doTheOther()
])
.then(([thisResult, thatResult, theOtherResult]) => { // The destructuring is optional, of course
// ...use them...
})
.catch(error => {
// ...handle/report error...
});
Promise.all([
client.query(q1).then(dosomething),
client.query(q2).then(dosomething)
])
.then(() => {
dosomething()};
}) // <== Added missing }
.catch(e => {
console.log(e); // <== Added missing ;
}); // <== Added missing ;
function doQuery(client, q) {
return new Promise((resolve, reject) => {
client.query(q, function(err, res) {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
关键位:
你通过一个iterable来保证。我用的都是上面的数组
无论事情以何种顺序完成,您都会以与iterable相同的顺序接收结果
承诺。如果任何操作被拒绝,所有人的承诺都会被拒绝。
在您发布的评论中,您发布了以下代码:
Promise.all([
client.query(q1,function(err,res){ dosomething();}),
client.query(q2,function(err,res){ dosomething();})
])
.then(() => {
dosomething()};
}) // <== Added missing }
.catch(e => {
console.log(e); // <== Added missing ;
}); // <== Added missing ;
…假设您希望仅在查询成功时调用doSomething,则无论查询成功还是失败,您的代码都在调用它
如果查询没有返回承诺,您应该将其包装成这样的内容:
Promise.all([
doThis(),
doThat(),
doTheOther()
])
.then(([thisResult, thatResult, theOtherResult]) => { // The destructuring is optional, of course
// ...use them...
})
.catch(error => {
// ...handle/report error...
});
Promise.all([
client.query(q1).then(dosomething),
client.query(q2).then(dosomething)
])
.then(() => {
dosomething()};
}) // <== Added missing }
.catch(e => {
console.log(e); // <== Added missing ;
}); // <== Added missing ;
function doQuery(client, q) {
return new Promise((resolve, reject) => {
client.query(q, function(err, res) {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
然后用这个:
Promise.all([
doQuery(client, q1).then(doSomething),
doQuery(client, q2).then(doSomething)
])
.then(() => {
dosomething()};
}) // <== Added missing }
.catch(e => {
console.log(e); // <== Added missing ;
}); // <== Added missing ;
您需要将回调封装在承诺中,以使用promise.all解决所有回调 因此: 如果您需要处理错误,则需要在出现错误时拒绝
希望这能有所帮助。如果没有看到代码,就无法100%确定,但是如果它们被正确地承诺,那么这听起来像是完美的代码,或者它没有发生……我给出了如下示例。Promise.all[client.queryq1,functionerr,res{dosomething;},client.queryq2,functionerr,res{dosomething;}],然后=>{dosomething};。catch=>{console.loge}@kaitlyn-注释中的代码工作不正常,如您所见:如果要显示正在使用的代码,最好使用问题的“编辑”链接。@kaitlyn-…但该代码看起来不正确。若查询接受回调,通常意味着它不是基于承诺的。我已经更新了答案以解决这个问题。1。这种内联操作通常容易出错;相反,创建一个包装器函数。2.该代码忽略了查询失败的可能性。它应该相应地检查err和branch?为什么不正确地显示它呢?