[英]AngularJS $q: How to chain promises then do parallel last in the chain?
[英]How do I do a callback chain with q?
我有些問題了解如何使用“q”(https://github.com/kriskowal/q)javascript的promises庫:
var delayOne = function() {
setTimeout(function() {
return 'hi';
}, 100);
};
var delayTwo = function(preValue) {
setTimeout(function() {
return preValue + ' my name';
}, 200);
};
var delayThree = function(preValue) {
setTimeout(function() {
return preValue + ' is bodo';
}, 300);
};
var delayFour = function(preValue) {
setTimeout(function() {
console.log(preValue);
}, 400);
};
Q.fcall(delayOne).then(delayTwo).then(delayThree).then(delayFour).end();
這只返回undefined ...
正如wroniasty指出的那樣,你需要從每個函數返回一個promise,但是你也應該盡可能抽象出任何面向回調的API(比如setTimeout
),並使用返回promises的API。
在setTimeout
的情況下,Q已經提供了Q.delay(ms)
,它返回一個將在指定的毫秒數后解析的promise,非常適合替換setTimeout
:
var delayOne = function() {
return Q.delay(100).then(function() {
return 'hi';
});
};
var delayTwo = function(preValue) {
return Q.delay(200).then(function() {
return preValue + ' my name';
});
};
var delayThree = function(preValue) {
return Q.delay(300).then(function() {
return preValue + ' is bodo';
});
};
var delayFour = function(preValue) {
return Q.delay(400).then(function() {
console.log(preValue);
});
};
Q.fcall(delayOne).then(delayTwo).then(delayThree).then(delayFour).done();
(注意: end
已被替換done
)
你得到“未定義”的原因是因為你鏈接的函數沒有返回任何東西:
var delayOne = function() {
setTimeout(function() {
return 'hi';
}, 100);
};
delayOne
調用setTimeout
,並且不返回任何內容( undefined
)。
要實現您的目標,您必須使用Q.defer
:
var delayOne = function() {
var d = Q.defer();
setTimeout(function() {
d.resolve("HELLO");
}, 100);
return d.promise;
};
var delayTwo = function(preValue) {
setTimeout(function() {
alert(preValue);
},
400);
};
delayOne().then ( delayTwo );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.