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)