场景是这样的,我得到一个get请求,它触发了一个返回Promise(promise1
)的函数,并且Promise返回函数本身具有一连串的诺言。
现在,我不想等待链结束,然后再将响应发送到前端,但想解决中间的某个问题。
现在,剩下的问题将作为注释添加到代码中,在这里更有意义。
app.get('/data', (req, res)=>{
promise1()
.then(result=>{
res.status(200).send({msg:result});
})
.catch(result=>{
res.status(400).send({msg:"Error"});
})
})
let promise1 = ()=>{
return new Promise((resolve, reject)=>{
promise2()
.then(result=>{
resolve(result);
/*What I want here is, just after the promise2 is resolved I want
to send the result back to the get router, so I can give quick response
and continue the slow processing in the backend which is promise3, but this
does not work as expected, I do not get the result in the router until promise3 is
resolved. But I do not want that. So any suggestions on how to achieve that.
*/
return promise3()
})
.then(result=>{
console.log("Done");
})
.catch(err=>{
console.log(err);
})
})
}
let promise2 = ()=>{
return new Promise((resolve, reject)=>{
resolve("Done");
})
}
let promise3 = ()=>{
return new Promise((resolve, reject)=>{
//Slow Async process
resolve("Done");
})
}
通过将
promise3
放入setTimeout
可以做到这一点,但我不确定如果那是正确的方法。
请忽略任何语法错误,这仅是为了提出问题的想法。
另外,我不确定这是否是正确的方法-如果我错了,请纠正我。
最佳答案
糟糕,我似乎过早关闭了How to properly break out of a promise chain?的副本。您真正想要的东西隐藏在源代码的注释中:
刚解决promise2
之后,我想将结果发送回get路由器,这样我就可以给出快速响应并继续在promise3
后端进行缓慢的处理,但是
return promise3()
不能按预期工作,直到promise3解决,我才在路由器中得到结果。
这更像Can I fire and forget a promise in nodejs (ES7)?-是的,可以。您只想从函数中传回要发送的结果,以便承诺链继续进行并可以立即发送。缓慢的后端处理将通过调用它来开始,但不通过将其返回到链中来等待它:
function promise1() {
return promise2().then(result => {
// kick off the backend processing
promise3().then(result => {
console.log("Backend processing done");
}, err => {
console.error("Error in backend processing", err);
});
// ignore this promise (after having attached error handling)!
return result; // this value is what is awaited for the next `then` callback
}).then(result => {
// do further response processing after having started the backend process
// before resolving promise()
return response;
})
}