A preface.

We often encounter such a hassle, multiple function execute sequentially, and return the result is not we expected order, reason is commonly caused by asynchronous operations, so we need a solution to deal with this problem, so as to make the asynchronous operation to perform in accordance with the synchronous way, so we can control the order of the asynchronous operation output

What are the problems caused by asynchronous operations

There can be many problems with asynchronous operations, and the following are two common ones

1. The results of function execution are not returned in order

function fn1(){
    console.log(111)
    setTimeout(function(){
        console.log('wait me 3000')},3000)}function fn2(){
    console.log(222)
}
fn1();
fn2();
Copy the code
/ / the result
/ / 111
/ / 222
//wait me 3000
Copy the code

The code above, if you expect the result to be

/ / / / 111wait me 3000
//222
Copy the code

Fn1 and fn2 are executed synchronously. Fn1 is executed first and then fn2, and 111 is printed when fn1 is executed. SetTimeout is executed three seconds later, but f has been executed before that n2

Is this caused by the setTimeout function setting the wait time too long? So now I’m going to set the time to 0

function fn1(){
    console.log(111)
    setTimeout(function(){
        console.log('wait me 3000')},0)}function fn2(){
    console.log(222)
}
fn1();
fn2();
/ / the result
/ / 111
/ / 222
//wait me 3000
Copy the code

The setTimeout function checks the execution queue to see if there is a queue before executing. If so, it will wait for other functions to finish executing before executing itself, so no matter if you set the time to 0, it will not change its last execution

2. The value in the asynchronous function cannot be obtained externally

Let’s look at the simplest example. My requirement is to print MSG outside the fn1 function

function fn1(){
    setTimeout(function(){
       msg='wait me 3000';
    },3000);
}
fn1();
Copy the code

So how do I get MSG

Use the callback function

function fn1(callback){
    setTimeout(function(){
       msg='wait me 3000';
       callback(msg);
    },3000);
}
fn1(data= >{
    console.log(data);//wait me 3000
});

Copy the code

The use of Promise

function fn1(){
    return new Promise(function(res,rej){
        setTimeout(function(){
            msg='wait me 3000';
            res(msg);
        },3000);
    })
}
fn1().then(data= >{
    console.log(data)
})
Copy the code

Async /await solution

The purpose of async/await is to cause asynchronous operations to be performed synchronously

Asynchronous operation synchronization?

What’s the difference between async/await and then() as in Promise

1. Async returns a Promise object

If an async keyword is added to a function that returns a value, the promise.solve () method is called internally to return a Promise object if the function executes successfully, and the Promise.reject() method is called to return a PR if the function executes abnormally Omise object

To get the result of an async function, call the Promise’s then or catch to register the callback

async function fn(){
    return '111'
}
console.log(fn());//Promise { '111' }
Copy the code

Since this is a Promise object, you can use then() to get the result returned

async function fn(){
    return '111'
}
fn().then(data= >{
    console.log(data)/ / 111
})
Copy the code

2.await

The function of async is described above. In general,async and await can be used together to synchronize asynchronous operations, and await means waiting for a function to be finished before the following code can be executed

function fn1(){
    return new Promise(resolve= >{
        setTimeout(function(){
            msg='wait me 3000';
            resolve(msg)
        },3000);
    });
}
async function asyncCall(){
    var result=await fn1();
    console.log(result); 
}
asyncCall();
Copy the code

If we had not waited for fn1 to finish before printing result, we would have gotten undefined

4. To summarize

In a lot of time, we hope to according to the synchronous way to obtain the result of an asynchronous function, such as login, we must return match in the background information on the page only after jump, therefore, it is important to make the asynchronous operation synchronization this knowledge, but this approach is based on the basis of Promise, so when learning the knowledge, must have Fully understand promises