How Promise concatenates multiple synchronous and asynchronous tasks

Promise's then() returns a new promise, which can be opened into a chain call of then(), and multiple synchronous/asynchronous tasks can be connected in series through then's chain call.

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);
})

Insert image description here
1. When the asynchronous task in the Promise has not been executed, it will not enter the .then callback function (see task 1)

2. When the callback function in .then is a synchronous task, the value can be passed to the next .then in the form of return+value (see task 2)

3. When the callback function in .then is an asynchronous task, the value cannot be passed to the next .then in the form of return+value, and it will be executed directly (see task 4)

4. When the callback function in .then is an asynchronous task, create a new Promise object to contain the asynchronous task. You need to add return before new Promise, so that the value can be passed to the next .then, and execution will not continue until the current .then is completed (see task 3)

Guess you like

Origin blog.csdn.net/weixin_46683645/article/details/118416945
Recommended