Async always returns a Promise object, so you can use then to process the result

1. Async returns a promise

 function sleep () {
   return new Promise(resolve= > {setTimeout(resolve,3000.2)})}async function f1() {
   return await sleep()
 }

console.log(f1());   / / below
f1().then(res= > console.log(res))  / / 2
Copy the code

2. Async does not return promises

async function f1() {
 return 'hello world'
}

console.log(f1()); / / below
f1().then(res= > console.log(res)) // 'helle world'
Copy the code

The result shows that async returns a promise object. If async returns an immediate promise object in the function, async wraps the immediate promise object with promise.resolve ()

3. If the asyn function does not return a value

async function foo() {
  console.log(1)}console.log(foo());
Copy the code

The state of the Promise returned by async functions will not change until all the Promise objects of the internal await command have been executed

That is, the callback to the then method is executed only when all asynchronous operations inside an async function have been executed.

const delay = timeout= > new Promise(resolve= > setTimeout(resolve, timeout));
async function f(){
    await delay(1000);
    await delay(2000);
    await delay(3000);
    return 'done';
}

f().then(v= > console.log(v)); // Wait 6s before printing 'done'
Copy the code

Normally, the await command is followed by a Promise, and if it is not, it will be converted to an immediately resolve Promise

async function  f() {
    return await 1
};
f().then( (v) = > console.log(v)) / / 1
Copy the code

If a reject state is returned, it is caught by the catch method.


Error handling of Async functions

// The correct way to write
// Functions that simulate Ajax
function ajax () {
    return new Promise((resolve, reject) = > setTimeout(reject,2000.1))}async function correct() {
    let a;
    try {
        a = await ajax()
    } catch (error) {
        throw new Error('Ajax interface error :'+error)
    }
    console.log(a)
    console.log(465)
}

correct()
Copy the code

He will stop the following code from executing

What processing does await do

‘await’ is literally waiting. ‘await’ is waiting for an expression whose return value can be a Promise object or other value.

Many people think that await is waiting for a subsequent expression to complete before continuing to execute code. In fact, await is a sign of relinquishing a thread. The “await” function will be executed once, and the “await” function will be executed immediately after the “await” function, and then the whole async function will be executed to execute the code in the js stack (more on this later). After the completion of this event loop, it will jump back to the async function and wait for the return value of await expression. If the return value is not a promise, it will continue to execute the code behind the async function. Otherwise, it will put the returned promise into the Promise Queue (promise Job Queue).

Async /await execution order

function testSometing() {
    console.log("Executive testSometing");
    return "testSometing";
}

async function testAsync() {
    console.log("Executive testAsync");
    return Promise.resolve("hello async");
}

async function test() {
    console.log("test start...");
    const v1 = await testSometing();// Key point 1
    console.log(v1);
    const v2 = await testAsync();
    console.log(v2);
    console.log(v1, v2);
}

test();

var promise = new Promise((resolve) = > { console.log("promise start.."); resolve("promise"); });// Critical point 2
promise.then((val) = > console.log(val));

console.log("test end...")
Copy the code

Results:

test start... Execute testSometing Promise start.. test end... TestSometing executes testAsync Promise Hello Async testSometing Hello asyncCopy the code

This is the order of js execution after async/await function. Let’s look at another example of adding async before testSometing

async function testSometing() {
    console.log("Executive testSometing");
    return "testSometing";
}

async function testAsync() {
    console.log("Executive testAsync");
    return Promise.resolve("hello async");
}

async function test() {
    console.log("test start...");
    const v1 = await testSometing();
    console.log(v1);
    const v2 = await testAsync();
    console.log(v2);
    console.log(v1, v2);
}

test();

var promise = new Promise((resolve) = > { console.log("promise start.."); resolve("promise"); });/ / 3
promise.then((val) = > console.log(val));

console.log("test end...")
Copy the code

Results:

test start... Execute testSometing Promise start.. test end... Promise testSometing executes testAsync Hello Async testSometing Hello asyncCopy the code