Promise如何串联多个包含同步和异步的任务

promise的then()返回一个新的promise,可以开成then()的链式调用,通过then的链式调用串联多个同步/异步任务

new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        console.log('我是异步任务1');
        resolve(111);
    },3000)
}).then(value => {
    
    
    console.log('任务1的值:', value);
    console.log('我是同步任务2');
    return 222;
}).then(value => {
    
    
    return new Promise((resolve, reject) => {
    
    
        setTimeout(() => {
    
    
            console.log('任务2的值:', value);
            console.log('我是异步任务3');
            resolve(333);
        },3000)
    }) 
}).then(value => {
    
    
	setTimeout(() => {
    
    
        console.log('任务3的值:', value);
        console.log('我是异步任务4');
       return 444;
    },3000)
}).then(value => {
    
    
	console.log('任务4的值:', value);
})

在这里插入图片描述
1. 当Promise中的异步任务没有执行完之前,不会进入.then的回调函数中(见任务1)

2. 当.then中的回调函数是同步任务时,可以通过 return+值 的形式将值传给下一个.then(见任务2)

3. 当.then中的回调函数是异步任务时,不可以通过 return+值 的形式将值传给下一个.then,并且会直接往下执行(见任务4)

4. 当.then中的回调函数是异步任务时,创建一个新的Promise对象来包含其中的异步任务。需要在new Promise之前加上return,这样才能将值传给下一个.then,并且在当前.then没有执行完之前不会往下执行(见任务3)

猜你喜欢

转载自blog.csdn.net/weixin_46683645/article/details/118416945