整理分享簡單用法。
可以參考 q 原始碼網頁 。
Basic
var Q = require("q"); function test() { // Do something return something; } function deferredTest() { var deferred = Q.defer(); // Do something // If success deferred.resolve(); // If success & want the value to be returned deferred.resolve(value); // If failed deferred.reject(); // If failed & want the error to be returned & handled deferred.reject(error); return deferred.promise; } Q.fcall(test); // Equals deferredTest();
Usage 1
deferredTest().then( function(successValue) { /* Do something */ }, function(rejectError) { /* Do something */ } );
Usage 2
deferredTest() .then(successHandler) .fail(rejectHandler) // .catch(rejectedHandler) may be used in modern engines .fin(finallyHandler); // .finally(finallyHandler) may be used in ...
Usage 3 : outputPromise == successValue
var outputPromise = deferredTest().then(function(successValue) { return successValue; });
Advanced : Q.all
var promises = []; promises.push(deferredFunction1, deferredFunction2, ...); Q.all(promises).then(handler);
Difference between Q.all and Q.allSettled
Q.all:promises 中,只要任何一個 rejected,馬上 rejected,不等沒做完的。Q.allSettled:是不管每一個 promise 是 fulfilled 或是 rejected,都會等全部做完。
沒有留言:
張貼留言