按顺序执行异步请求

本文总结了三种处理异步请求顺序的方法:1) 使用Promise实现链式调用确保执行顺序;2) 利用Generator函数配合co库控制流程;3) 结合setTimeout模拟异步操作的先后顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

总结常用方式

1、Promise:

function first(){
    return new MyPromise(function (resolve, reject) {
        console.log('执行1')
        setTimeout(() => {
            console.log('1请求结束')
            resolve('1返回参数')
        }, 1000);
    });
}
function second(){
    return new MyPromise(function (resolve, reject) {
        console.log('执行2')
        setTimeout(() => {
            console.log('2请求结束')
            resolve('2返回参数')
        }, 1000);
    });
}
function third(){
    return new MyPromise(function (resolve, reject) {
        console.log('执行3')
        setTimeout(() => {
            console.log('3请求结束')
            resolve('3返回参数')
        }, 1000);
    });
}

first().then(second).then(third).then( res => {
    console.log(3返回参数)
})


2、Generator

function first(msg) {
    setTimeout(() => {
        console.log('第一个请求 compile', msg),
            it.next('第一个请求 result');
    }, 2000)
}
function second(msg) {
    setTimeout(() => {
        console.log('第二个请求 compile', msg),
            it.next('第二个请求 result');
    }, 2000)
}
function third(msg) {
    setTimeout(() => {
        console.log('第三个请求 compile', msg),
            it.next('第三个请求 result');
    }, 2000)
}

function *excute(){
    var result = yield first("执行开始");
    var data2 = yield second(result);
    var data3 = yield third(data2);
    console.log('执行结束', data3);
}


 
var it = main();
it.next();
console.log("执行完毕");

3、setTimeout

function first() {    
    setTimeout(() => {        
        console.log('执行1')        
        setp2('1传递的参数')    
    }, 2000);
}
function second(data) {    
    setTimeout(() => {        
        console.log('执行2', data)        
        setp3('2传递的参数')    
    }, 2000);
}
function third(data) {    
    setTimeout(() => {        
        console.log('执行3', data)    
    }, 2000);
}

first();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值