场景是这样的,我收到一个 get 请求,它触发了一个返回 Promise (promise1
) 的函数,Promise 返回函数本身有一个 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? 的副本过早关闭了.你真正想要的隐藏在源代码的注释中:
Just after the
promise2
is resolved i want to send the result back to the get router so i can give give quick response and continue the slow processing in the backend which ispromise3
, butreturn promise3()
does not work as expected, i do not get the result in the router until promise3 is resolved.
这更像是 Can I fire and forget a promise in nodejs (ES7)? - 是的你可以。您只需要return
要从函数发回的结果,以便 promise 链继续处理并立即发送。缓慢的后端处理将通过调用它来启动,但不会通过将它返回到链中来等待它:
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;
})
}
关于javascript - 从链中解决 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45128444/