Promise

Promise is a standardized asynchronous management method provided by the JavaScript language. The general idea is that functions that require IO, wait, or other asynchronous operations do not return real results, but instead return a “Promise” that the caller can, at the appropriate time, Choose to wait for the Promise to be fulfilled (via a callback from the Promise’s then method).

An example of basic use of Promise is as follows:

    function sleep(duration) {
        return new Promise(function(resolve, reject) {
            setTimeout(resolve,duration);
        })
    }
    sleep(1000).then( () = > console.log("finished"));
Copy the code

This code defines a function, sleep, that waits for the length specified by the passed argument.

The Promise’s then callback is an asynchronous execution. To examine the order of execution in the Promise function, let’s look at a code example:

    var r = new Promise(function(resolve, reject){
        console.log("a");
        resolve()
    });
    r.then(() = > console.log("c"));
    console.log("b")
Copy the code

After we execute this code, notice the order of output is A, B, and C. Before entering console.log(” b “), there is no doubt that R has reached resolve, but the Promise’s resolve is always an asynchronous operation, so C cannot appear before B.

We found that d must occur after C, regardless of code order, because promises generate microtasks inside the JavaScript engine, and setTimeout is the browser API that generates macro tasks.

Promise is a definition in JavaScript, but when we actually write code, it doesn’t seem to be any easier to write as a callback, but starting with ES6 we have async/await, a syntactic improvement that works with promises, Can effectively improve code structure.

New feature: async/await

Async /await is a new feature in ES2016 that provides a way to write asynchrons with code structures such as for and if. Its runtime base is Promise, so with this relatively new feature in mind, let’s take a look at its basic usage.

Async functions must return promises, and we consider all functions that return promises to be asynchronous functions.

The power of async is that it can be nested. When we define a batch of atomic operations, we can use async functions to compose new async functions.

function sleep(duration) {
    return new Promise(function(resolve, reject) {
        setTimeout(resolve,duration); })}async function foo(name){
    await sleep(2000)
    console.log(name)
}
async function foo2(){
    await foo("a");
    await foo("b");
}
Copy the code