Write it up front

They always learn to forget, forget to learn again, this time simply write down!

Use it as a tool document at any time.

Asynchronous operations

  • There are many asynchronous operations in JSPromiseorasync awaitAsynchronous operations can be queued.
  • It can be executed in the desired order, returning the desired results.
  • This is especially true for data requests, of course.

Why usePromise

  • Chain call, the code is clearer.
  • Do not use nested callback methods orsetTimeout
  • The previous implementation is complete and sentresolveOnly later can it be executed, in the desired order, and return the desired result.

Promise

  • thenTo obtainresolveThe value that
console.log('=== START ===');
new Promise(resolve => {
    setTimeout(() => {
        resolve('=== 111 ===');
    }, 1000);
}).then(msg => {
    console.log(msg);
    return new Promise(resolve => {
        setTimeout(() => {
            resolve('=== 222 ===');
        }, 1000);
    })
}).then(msg => {
    console.log(msg);
    return new Promise(resolve => {
        setTimeout(() => {
            resolve('=== 333 ===');
        }, 1000);
    })
}).then(msg => {
    console.log(msg);
    console.log('=== END ===');
});
Copy the code

async await

  • ispromiseGrammar sugar, grammar is more likeSynchronous programs, recommended writing.
  • asyncIf added to the function, it returnspromise
  • awaitFunction is equal to thethen
  • awaitMust be onasyncUsed in a function defined by.

Use then to get the value of resolve

(async () => { console.log('=== START ==='); await new Promise((resolve,reject) => { setTimeout(() => { resolve('=== 111 ==='); }, 1000); }).then(msg => { console.log(msg); }); await new Promise(resolve => { setTimeout(() => { resolve('=== 222 ==='); }, 1000); }).then(msg => { console.log(msg); }); await new Promise(resolve => { setTimeout(() => { resolve('=== 333 ==='); }, 1000); }).then(msg => { console.log(msg); console.log('=== END ==='); }); }) ();Copy the code

Pass the resolve value to the declared variable with await

(async () => { console.log('=== START ==='); let p1 = await new Promise((resolve,reject) => { setTimeout(() => { resolve('=== 111 ==='); }, 1000); }); console.log(p1); let p2 = await new Promise(resolve => { setTimeout(() => { resolve('=== 222 ==='); }, 1000); }); console.log(p2); let p3 = await new Promise(resolve => { setTimeout(() => { resolve('=== 333 ==='); }, 1000); }); console.log(p3); console.log('=== END ==='); }) ();Copy the code

Continuously updated