我有一个来自在线教程的示例,我想知道如何将每个转换为异步调用?
编辑 - 基本上我希望承诺以异步方式继续每个调用,或者它是如何工作的。我是承诺的新手,一个承诺意味着单个异步调用或一个承诺可以有几个异步调用,然后在最后回调,
如果我有三个函数调用,我如何将它们链接为异步,现在它们都会按顺序立即触发?
编辑2 - 基于Joel的支持学习改进了我的问题,我现在是个小提琴 http://jsfiddle.net/smartdev101/eLxxpjp3/
var q = require('q');
var defer = q.defer();
defer.promise
.then(function(weapon){
setTimeout(function(){console.log('wait')}, 2000);
console.log("You can have my " + weapon);
return "bow";
})
.then(function(weapon){
console.log("and my " + weapon);
return "axe";
})
.then(function(weapon){
console.log("and my " + weapon);
});
defer.resolve("sword");
答案 0 :(得分:2)
也许这会给你你所期望的(虽然我不确定你的期望):
var q = require('q');
function waitAndSpeak(words) {
var defer = q.defer();
setTimeout(function(){
defer.resolve(words)
}, 2000);
return defer.promise;
}
waitAndSpeak("sword").then(function(weapon) {
console.log("You can have my " + weapon);
return waitAndSpeak("bow");
}).then(function(weapon) {
console.log("and my " + weapon);
return waitAndSpeak("axe");
}).then(function(weapon) {
console.log("and my " + weapon);
}).done();