qについてのメモ whenを使う whenでQ.when(5, onFulfilled)とQ(5).then(onFulfilled)は同じ Q.when(1) .then(function(a){ console.log(a) var d = Q.defer(); setTimeout(function() { a += 1; d.resolve(a); }, 1000); return d.promise; }) .then(function(a){ console.log(a) var d = Q.defer(); setTimeout(function() { a += 1; d.resolve(a); }, 500); return d.promise; }) .done(function(a){ console.log(a) }); notifyを使う notify Q.when(1) .then(function(a){ var d = Q.defer(); setTimeout(function() { for (var i = 1; i < 10; i++) { d.notify(i); } d.resolve("foo"); }, 1000); return d.promise; }) .then( function(a){ console.log(a) }, null, function(a) { console.log(a); } ); //1 //2 //3 //4 //5 //6 //7 //8 //9 //"foo" allを使う allはすべてがfulfillな場合は結果の配列を返す。 rejectされた場合があったときは最初にrejectされたものを返す。 Q.all( [ function(){ var d = Q.defer(); setTimeout(function() { d.resolve(100); }, 1000); return d.promise; }(), function(){ var d = Q.defer(); setTimeout(function() { d.resolve(123); }, 500); return d.promise; }(), function(){ var d = Q.defer(); setTimeout(function() { d.resolve("8"); }, 550); return d.promise; }() ] ) .then(function(a){ console.log("onFulfilled"); console.log(a); },function(a){ console.log("onRejected"); console.log(a); }); //onFulfilled //[100, 123, "8"] Q.all( [ function(){ var d = Q.defer(); setTimeout(function() { d.reject(100); }, 1000); return d.promise; }(), function(){ var d = Q.defer(); setTimeout(function() { d.resolve(123); }, 500); return d.promise; }(), function(){ var d = Q.defer(); setTimeout(function() { d.reject("8"); }, 550); return d.promise; }() ] ) .then(function(a){ console.log("onFulfilled"); console.log(a); },function(a){ console.log("onRejected"); console.log(a); }); //onRejected //"8" Q.all( [ function(){ var d = Q.defer(); setTimeout(function() { d.resolve(100); }, 1000); return d.promise; }(), function(){ var d = Q.defer(); setTimeout(function() { d.resolve(123); }, 500); return d.promise; }(), function(){ var d = Q.defer(); setTimeout(function() { d.resolve("8"); }, 550); return d.promise; }() ] ) .spread(function(a1, a2, a3){ console.log("onFulfilled"); console.log(a1); console.log(a2); console.log(a3); },function(a1,a2, a3){ console.log("onRejected"); console.log(a1); console.log(a2); console.log(a3); }); //onFulfilled //123 //100 //"8" Q.all( [ function(){ var d = Q.defer(); setTimeout(function() { d.reject(100); }, 1000); return d.promise; }(), function(){ var d = Q.defer(); setTimeout(function() { d.resolve(123); }, 500); return d.promise; }(), function(){ var d = Q.defer(); setTimeout(function() { d.reject("8"); }, 550); return d.promise; }() ] ) .spread(function(a1, a2, a3){ console.log("onFulfilled"); console.log(a1); console.log(a2); console.log(a3); },function(a1,a2, a3){ console.log("onRejected"); console.log(a1); console.log(a2); console.log(a3); }); //onRejected //"8" //undefined //undefined