在JavaScript中實現異步Promises的工具:q
一個工具用于在JavaScript中制作和編寫異步Promises。Promises是一種令代碼異步行為更加優雅的抽象,它很有可能是JavaScript的下一個編程范式,一個Promise即表示任務結果,無論該任務是否完成。 每個Promise都擁有一個叫做then的唯一接口,當Promise失敗或成功時,它就會進行回調。它代表了一種可能會長時間運行而且不一定必須完成的操作結果。這種模式不會阻塞和等待長時間的操作完成,而是返回一個代表了承諾的(promised)結果的對象。

On the first pass, promises can mitigate the “Pyramid of Doom”: the situation where code marches to the right faster than it marches forward.
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
}); With a promise library, you can flatten the pyramid.
Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
// Do something with value4
})
.catch(function (error) {
// Handle any error from all above steps
})
.done();
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!