我该怎么做符合Q回调链? [英] How do I do a callback chain with q?
本文介绍了我该怎么做符合Q回调链?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一些问题,了解如何使用Q(https://github.com/kriskowal/q)一对JavaScript库的承诺:
I some problems understanding how to use "q" (https://github.com/kriskowal/q) a promises library for javascript:
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 ...
this only returns undefined...
推荐答案
在得到未定义的原因是因为你链接不返回任何东西的功能:
The reason you get "undefined" is because the functions you are chaining are not returning anything:
var delayOne = function() {
setTimeout(function() {
return 'hi';
}, 100);
};
delayOne
要求的setTimeout
,并没有返回值(未定义
)。
delayOne
calls setTimeout
, and returns nothing (undefined
).
要实现你的目标,你必须使用 Q.defer
:
To achieve your goal you must use 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 );
这篇关于我该怎么做符合Q回调链?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文