このようなシナリオでは、私は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");
})
}
はsetTimeout
でpromise3
を置くことによって、これを行うことができたが、それは正しい方法であれば、私は を確認していません。
文法上の間違いを無視してください。これは質問の考え方を示すことに過ぎません。
また、これが正しい方法であるかどうかはわかりません。私が間違っている場合は正しいと思います。
あなたはpromise1関数に解像度を渡し、その後の内部または内部res.sendを使用することができます他の埋め込み関数の –
@タマンゴーいいえ、それは絶対に何をすべきではありません。このようなコールバックを渡す必要がないという理由で、約束の抽象化が存在します。 – Bergi
['Promise'コンストラクタの反パターンを避ける](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-constructionそれは避けてください!) – Bergi