如何解决jQuery Promise函数链接
我正在尝试创建一系列链接在一起的功能。下面是我想要的,但是我希望能够单独调用任何函数来启动序列。例如,如果我调用one(),它将运行one(),然后运行two(),然后运行three(),然后运行complete()。如果我调用three(),它将运行3,然后运行complete()。有没有一种方法可以将每个函数“链接”到其下面的函数,而无需像one().then(two).then(three).then(complete);
那样调用它,而只是一个()或两个(),等等?
function one() {
var d = $.Deferred();
console.log('one');
setTimeout(function() {
d.resolve();
},5000);
return d.promise();
}
function two() {
var d = $.Deferred();
console.log('two');
setTimeout(function() {
d.resolve();
},5000);
return d.promise();
}
function three() {
var d = $.Deferred();
console.log('three');
setTimeout(function() {
d.resolve();
},5000);
return d.promise();
}
function complete() {
console.log('done');
}
one().then(two).then(three).then(complete);
解决方法
假设顺序始终相同,只需在每个命令中添加一个12345 'user1: who are the users on this server?'
23456 "user2: oh that' easy my name is harry\nuser3 is adam\nuser4 is max"
12345 'user1: okay got that'
,然后在其中依次调用下一个。
then()
function one() {
var d = $.Deferred();
console.log('one');
setTimeout(d.resolve,1000);
return d.promise().then(two);
}
function two() {
var d = $.Deferred();
console.log('two');
setTimeout(d.resolve,1000);
return d.promise().then(three);
}
function three() {
var d = $.Deferred();
console.log('three');
setTimeout(d.resolve,1000);
return d.promise().then(complete);
}
function complete() {
console.log('done');
}
one();
setTimeout(()=>{console.log('Start at three'); three()},5000)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。