2017-07-16 168 views
0

因此,情況是這樣的,我得到一個獲取請求,它觸發一個函數返回一個Promise(promise1),並且承諾返回函數本身有一個承諾鏈。 現在我不想在發送響應到前端之前等待鏈條結束,但想要在中間的某個地方解決。解決承諾從鏈

現在問題的其餘部分被放在代碼中作爲註釋,它更有意義。

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

能由於投入setTimeoutpromise3要做到這一點,但我不知道 如果這是正確的做法。

請忽略任何語法錯誤,這只是爲了給出這個問題的想法。

另外我不確定這是否是正確的方法 - 糾正我,如果我錯了。

+0

你可以通過RES到promise1函數,然後使用它或內內res.send的其他嵌入式功能。 –

+1

@Tamango不,這絕對不是應該做的。承諾抽象是有原因的:不需要傳遞這樣的回調 – Bergi

+1

避免['Promise'構造函數反模式](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction -antipattern和知識對避免-吧)! – Bergi

回答

3

糟糕,看起來像我過早關閉作爲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; 
    }) 
}