从链中解决承诺

时间:2017-07-16 12:11:40

标签: javascript node.js promise

所以场景是这样的,我得到一个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 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 acheive 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,但我不确定 如果这是正确的方法。

请忽略任何语法错误,这只是为了提出问题的想法。

此外,我不确定这是否是正确的做法 - 如果我错了,请纠正我。

1 个答案:

答案 0 :(得分:4)

哎呀,看起来我过早地关闭了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)? - 是的,你可以。您只需要return要从函数发回的结果,以便承诺链继续使用,并可以立即发送。慢速后端处理将通过调用它来启动,但通过将其返回到链中等待它:

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;
    })
}