preface

Promise\color{#33CC99}{Promise} Basic use of Promise before reading this article

Promise basic usage

The Promise Saucepan API

Macro and micro tasks

(There are too many articles of Da Shen, so I will not expand on them here.)

Which apis are microtasks?

Then, catch, finally

When to join the microtask queue?

When a Promise goes non-pending, the API’s callback is added to the microtask queue

  new Promise((resolve,reject) => {
    resolve()
  }).then(() => {
    console.log("then")
  })
Copy the code

In the example above, the then callback () => {console.log(“then”)} is put into the microtask

The example analysis

gas

A fool example

  • point

Execution sequence of macro task and micro task

  • code
Promise.resolve()
  .then(() => {
    console.log("then");
    Promise.resolve().then(() => {
      console.log("then-1");
    });
  })
console.log("out")
Copy the code
  • The results of
out
then
then-1
Copy the code
  • Analysis of the
  1. Code execution toPromise.resolve().then
  2. The former Promise is resolved\color{#33CC99}{resolved} Resolved, so the then callback is put into the microtask
The microtask queue is pressed into code: () => {console.log("then"); Promise.resolve().then(() => { console.log("then-1"); }); }Copy the code
  1. Continue to performconsole.log("out")And the output out
  2. View microtasks, execute, output then; Proceed toPromise.resolve().then
  3. Promise has resolved\color{#33CC99}{resolved} Resolved state, then callback into the microtask
() => {console.log("then-1"); }Copy the code
  1. View the microtask, there is only one microtask, execute, then-1

Idiot example

  • point

Execute promise.resolve () in the THEN callback, which equals that the Promise state returned by the THEN is resolved

  • code
Promise.resolve()
  .then(() => {
    console.log("then1");
    Promise.resolve().then(() => {
      console.log("then1-1");
    });
  })
  .then(() => {
    console.log("then2");
  });
console.log("out")
Copy the code
  • The results of
out
then1
then1-1
then2
Copy the code
  • Analysis of the
  1. Go to the first onePromise.resolve().thenAnd its callback is pressed into microtasks
Microtask queue pressing code: () => {console.log("then1"); Promise.resolve().then(() => { console.log("then1-1"); }); }Copy the code
  1. Moving on, the second then is a callback because the previous Promise state has not yet been determined() => { console.log("then2"); }
    Don’t get caught up in microtasks \color{#33CC99}{
  2. Execute console.log(“out”) to print out
  3. Execute the micro task, output then1; performPromise.resolve().thenIts callback() => { console.log("then1-1"); }In the micro task, the state of the first THEN becomes resolved, so the callback of the second THEN is also stuck in the micro task
Micro task queue into code: [/ / micro task 1 () = > {the console. The log (" then1-1 ");}, micro / / task 2 () = > {the console. The log (" then2 ");}]Copy the code
  1. Execute the microtask, output then1-1,then2

The preconditions

Begin to understand example

  • point

In a THEN callback, return a non-promise

  • code
Promise.resolve()
  .then(() => {
    console.log(1);
    Promise.resolve()
      .then(() => {
        console.log(2);
        return 3;
      })
      .then((data) => {
        console.log(data);
      });
  })
  .then(() => {
    console.log(4);
  })
  .then(() => {
    console.log(5);
  })
  .then(() => {
    console.log(6);
  });
Copy the code
  • The results of
One, two, four, three, five, sixCopy the code
  • Analysis of the
  1. Output 1, which is internalPromise.resolve()Changes the state of the first THEN, so the following code is pushed into the microservice
Micro task queue into code: [() = > {the console. The log (2); the return 3;}, () = > {the console. The log (4);}]Copy the code
  1. Perform microservice 1, output 2, return 3, and push the subsequent then callback into the microservice queue
(data) => {console.log(data); }Copy the code
  1. Perform microservice 2, output 4, and push the subsequent THEN callback into the microservice queue
Micro task queue into code: [(data) = > {the console. The log (data);} () = > {the console. The log (5);}]Copy the code
  1. Perform microtask 1, input parameter 3, output 3; Perform microservice 2, output 5, press subsequent callback into microtask, and then perform output 6

Level out example

  • point

In the then callback, return a promise.resolve()

  • code
Promise.resolve()
  .then(() => {
    console.log(1);
    Promise.resolve()
      .then(() => {
        console.log(2);
        return Promise.resolve(3);
      })
      .then((data) => {
        console.log(data);
      });
  })
  .then(() => {
    console.log(4);
  })
  .then(() => {
    console.log(5);
  })
  .then(() => {
    console.log(6);
  })
  .then(() => {
    console.log(7);
  });
Copy the code
  • The output
1, 2, 4, 5, 6, 3, 7Copy the code
  • Analysis of the
  1. You taste, you fine taste
  2. In simple terms, if resolve is returned in then, the subsequent THEN will lag behind two microtask queues, as shown hereconsole.log(5);andconsole.log(6);, and then pressed into the microtask queue

Resurrection example

  • point

In the then callback, new Promise and resolve, return a promise.resolve()

  • code
new Promise((resolve, reject) => {
  console.log("1");
  resolve();
})
.then(() => {
    console.log("2");
    new Promise((resolve, reject) => {
        console.log("3");
        resolve();
    })
    .then(() => {
        console.log("4");
    })
    .then(() => {
        console.log("5");
    });
    return new Promise((resolve, reject) => {
        console.log("6");
        resolve();
    })
    .then(() => {
        console.log("7");
    })
    .then(() => {
        console.log("8");
    });
})
.then(() => {
    console.log("9");
});
Copy the code
  • The output
1, 2, 3, 6, 4, 7, 5, 8, 9Copy the code
  • Analysis of the
  1. Output 1, 2,
  2. After 3, the first THEN callback: internal the first Promise state changes to Resolved and registers console.log("4")Micro tasks; At this point, the macro task is not finished, and the execution continues to return, new the second internal Promise, and executes the synchronization codeconsole.log("6"), change the Promise state to Resolved, will followconsole.log("7")Register to the microtask queue; Note that the state of the first THEN has not changed, so the second THEN callback is not registeredconsole.log("9")To the microtask queue
  3. Execute the microtask and output 4,7, 5,8. The first return returns the Promise state as resolved and registers the second then callbackconsole.log("9")Go to the microtask queue and execute

then

Wait for me to chase after chase after a star to fill up again, I am afraid is not practice jin Dan….

Upgrade example

  • point

Promise is combined with Async

  • code
async function async () {
  console.log('async start');
  await new Promise(resolve => {
    console.log('promise')
  })
  console.log('async success');
  return 'async end'
}
async().then(res => console.log(res))
Copy the code
  • The output
async start
promise
Copy the code
  • Analysis of the

Note here that since the promise state behind await has not changed, it is always pending, the subsequent code will not execute! Can only wait!

The example of a mire storm

  • Understand the return in then
  • code
new Promise(resolve => { resolve(); }).then(() => { setTimeout(() => { console.log(1); Promise.resolve(); }, 4000) }).then(() => { setTimeout(() => { console.log(2); }, 1000)})Copy the code
  • The output
2
1
Copy the code
  • Analysis of the

See? It’s 2, 1, not 1, 2! The reason is that in the first then, although resolve is delayed by 4s, it does not return!! When there is no return in then or when a non-promise is returned, the then state automatically becomes Resolved!

reference

Do you really use Promise?