0
Koa.js屈服值我有一個使用koa.js
一個應用程序,以及用於上下文我在對接不嚴格遵循請求/響應模式的外部系統的過程。 IE瀏覽器。在「請求」之後,它可能會或可能不會回答。與爭用條件
我能夠符合我的要求,這些反應,但隨後我無法將其寫入koa.js響應:
r.get('/...', *function() {
// (1) cannot yield since it will block and never call (2) ?
callbacks.storeCb(howToMatchAnEventualResponse, function(err, resp) { // may never get called depending about how the external system answers
console.log("I should answer the http req now"); // how to answer the request from here ?
});
// has to be done after storingCb, this may or may not trigger the callback above
externalSystem.sendMessage(msg); // (2)
// something similar will have to be done in the callback instead
this.body = {
success : true,
response : ''
};
});
所以我的問題是,我怎麼使用回答HTTP請求koa在我的回調(或類似的東西)中,以及當回調沒有被調用時(即,可能延遲之後)如何發送一個空的答案?
我在猜測,我正在尋找類似於Promise.race()
的東西,但對於koa
,所以使用yield
。
在興亞發電機抽象主要是用來簡化路由邏輯(即處理請求),而不是必須使用來解決所有問題(它不能)的抽象。 「Koa方式」實際上是將你更復雜的異步邏輯與返回承諾的函數一起包裝,然後在你的路由中產生它們(在你的情況下爲'Promise.race()')。通過這種方式,您可以在路由之外保持複雜性,但只要您需要解決此問題,您還可以編寫簡單的基於回調的異步代碼。把發電機看作你在路由處理程序中使用的工具。 – danneu
兩件事情:1)'Promise.race'在兩個ES2015和藍鳥2)藍鳥建議使用'BluebirdPromise.any',而不是'BluebirdPromise.race'因爲前者標記甚至拒絕承諾爲「勝利者」的http:/ /bluebirdjs.com/docs/api/promise.race.html –