2017-07-16 11 views
0

このようなシナリオでは、私は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 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

あなたはpromise1関数に解像度を渡し、その後の内部または内部res.sendを使用することができます他の埋め込み関数の –

+1

@タマンゴーいいえ、それは絶対に何をすべきではありません。このようなコールバックを渡す必要がないという理由で、約束の抽象化が存在します。 – Bergi

+1

['Promise'コンストラクタの反パターンを避ける](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-constructionそれは避けてください!) – 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; 
    }) 
} 
関連する問題