Promise first specify the callback function or change the state first?

1. It is possible, under normal circumstances, the callback function is specified first and then changed, or it is possible to change the state first and then specify the callback function

2. How to first change the state and then specify the callback?

2.1 Call resolve()/reject() directly in the executor

let p = new Promise((resolve,reject) => {
    
    
       resolve('ok')
     })
     p.then(value => {
    
    
         console.log(value);
     })

2.2 Delay longer before calling then(), add a timer

 let p = new Promise((resolve,reject) => {
    
    
        setTimeout(function(){
    
    
            resolve('ok')
        },1000)
     })
     setTimeout(function(){
    
    
        p.then(value => {
    
    
         console.log(value);
     })
     },3000)

3. How to specify the callback first and then change the state?

3.1 Directly call the asynchronous call relove()/reject() in the executor

  let p = new Promise((resolve,reject) => {
    
    
        setTimeout(function(){
    
    
            resolve('ok')
        },1000)
     })
     p.then(value => {
    
    
         console.log(value);
     })

4. When will the data be available?

4.1 If you specify the callback function first, when the state changes, call the callback function to get the data

4.2 If you change the state first, when the callback function is specified, call the callback function to get the data

Guess you like

Origin blog.csdn.net/yrfjygb/article/details/113882967
Recommended