The rest of your life is very expensive, and strive to live as you want, I wish you can wear sneakers, train and sweat like rain, also can wear high heels chic beauty, not youth, not their own.


Ha ha ~ serious appearance, very charming ☺️☺️☺️

Promise

Basic grammar and usage

Promisedefine

The Promise object is used to represent the final completion (or failure) of an asynchronous operation and its resulting value. ES6 has a new built-in class: the Promise Promise/contract pattern, which effectively handles asynchronous programming

Promisedescribe

A Promise object represents values that are not necessarily known when the Promise is created. It allows you to associate the eventual success return value or failure cause of an asynchronous operation with the appropriate handler. This allows the asynchronous method to return the same value as the synchronous method: the asynchronous method does not immediately return the final value, but instead returns a Promise instance

Promise method

Promise.all(iterable)

  • grammar:Promise.all(iterable)
  • Argument: an iterable
  • The return value: Returns aPromiseThe instance
    • In this instance可迭代All within the parameterspromiseDo”(resolved)“Or not included in the parameterpromiseWhen the callback is complete(resolve);Promise.allThe returnedpromise asynchronousThe earth becomes complete.
    • If the parameterpromise There is a failure(rejected), this instance callback failed(reject)The cause of failure is the first failurepromiseResults.
    • The iterable passed in is empty,Promise.allsynchronousTo return a completed(resolved)The state of thepromise. Look at the following example

Promise.any()

  • grammar:Promise.any(iterable);
  • Argument: an iterable object
  • The return value: Just one of thempromiseIf it succeeds, return the one that has succeededpromise

Promise.race()

  • grammar:Promise.race(iterable);
  • Argument: an iterable object
  • The return value: Returns apromise, once one of the iteratorspromiseResolved or rejected, returnedpromiseIt will be resolved or rejected. (As long as a success or failure is executed, the returned promise instance succeeds or fails.)

Promise.reject()

  • grammar:Promise.reject(reason);
  • Parameter: indicates the reason the Promise was rejected
  • The return value: Returns a failure cause asreasonpromiseThe instance

Promise.resolve()

  • grammar:Promise.reject(value);
  • parameter:PromiseObject resolution argument, which can also be onePromiseObject, or athenable
  • The return value: returns a parsed object with the given valuePromiseObject if the argument itself is onePromiseObject, returns this directlyPromiseObject.

Promise.prototype.catch()

  • grammar:
    • p.catch(onRejected);
    • p.catch(function(reason) {});
  • parameter:.then()Method to inject the second functionreason
  • The return value:catch()Method returns aPromiseAnd handle the rejection

Promise.prototype.finally()

  • describe: Returns aPromise. inpromiseAt the end of the day, whatever the result isfulfilledOr is itrejectedExecutes the specified callback function
  • grammar:
    • p.finally(onFinally);
    • Of (function() {// return state (resolved or rejected)});
  • parameter:PromiseCalled after the endFunction.
  • The return value: Returns a settingfinallyOf the callback functionPromiseObject.

Promise.prototype.then()“Scroll down for detailed use”

  • The then() method returns a Promise. It needs at most two arguments: a callback to Promise’s success and failure cases.
  • grammar:
    • p.then(onFulfilled[, onRejected]);
    • p.then(value => {// fulfillment}, reason => {// rejection});
  • parameter:
    • onFulfilled
    • onRejected
  • The return value: Returns a settingfinallyOf the callback functionPromiseObject.

PromiseThe three concepts of

  1. executorfunction
  • new PromiseWill be executed immediatelyexecutorFunction,executorFunction manages an asynchronous programming code (as does synchronous code)OKAt this timePromiseThe state ispending; By executing when our asynchronous operation succeeds or failsresolveorrejectFunction, which effectively changes the instance state to a successful or failed state, i.e. frompendingintoThis is a big pity/Rejected (fail).; If the code error case, also change the state toRejected (failure);
  1. The instance
  • Each Promise instance has it[[PromiseState]]and[[PromiseResult]]Method,[[PromiseState]]ispromiseStatus:pending,fulfilled/resolve,rejectedThree states;[[PromiseResult]]ispromiseValue: The default value isundefined, generally stores the result of success or the cause of failure.
  1. PromiseThe prototype approach.then(): Used to control successful or failed operations
  • Instances can call.then()It stores two methods:resultreason(both functions); whenp1The instance status is changed tofulfilledIs the first function that the notification passes(result)To perform,result is[[PromiseResult]]The value of the; whenp1The instance status is changed torejectedThe second function of the notification pass(reason)To perform,reasonis[[PromiseResult]]The value of the
  • Whether or not based onTHENInjected method, executeresolve/reject“, “Modify state and value” is synchronous and will be processed immediately, but “notify corresponding injection method execution” is asynchronous operation, will not be processed immediately, just put it in the waiting task queue, when other things are finished, return again, notify corresponding injection method execution
  • .then(onfulfilled, onrejected): performthenThe method is simply to takeonfulfilled/onrejectedThe function is saved (the saved operation is synchronous), but the function has not yet been executed, whenpromiseWhen the status changes to success or failure, the corresponding function will be triggered to execute,thenIs an asynchronous microtask

PromsieHow is asynchronous programming controlled

  • new PromiseThe created instance, its status and results, depend on:
    • executorIn the functionresolve/rejectperform
    • executorWhether an error is reported during function execution
  • perform.thenMethod returns a brand newpromiseThe instance
  1. new Promise“To create onepromiseInstance, at this time inexecutorFunction to manage a set of asynchronous code
  2. If the asynchronous operation succeeds or fails, perform itresolve/rejectIn order to controlpromiseThe state and results of the instance
  3. Based on status and results, you can control based.thenWhich of the two injected methods is executed

Watching the chestnuts

  1. The order in which the following code is executed (executorFunctions govern asynchronous programming)
    • new PromiseConstructor execution
    • performexecutorFunction: Sets an asynchronous timer
    • Execution instance.then(result, reason)Inject two methods, and the injected methods are saved (they are not executed at this point)
    • Waiting for the1000ms
    • Execute timer callback function: by executingresolvechangepromiseStatus and value
    • Prior notice based on.then()Either of the injected methods executes
let p1 = new Promise(function (resolve, reject) { 
  // Execute the executor function immediately after new Promsie, which manages an asynchronous programming code in the executor function (state pending); When the asynchronous operation reaches the specified time and starts to execute (which can be interpreted as the asynchronous operation succeeds), then we can perform resolve to change the promise state to depressing.
  setTimeout(function(){
    resolve('OK');
  }, 1000)});console.log(p1); // Promise {<pending>}__proto__: Promise[[PromiseState]]: "pending"[[PromiseResult]]: undefined

p1.then(result= >{
  // When the state of p1 instance is fulfilled, the first function will be executed, and result is the value of [[PromiseResult]]
  console.log('success', result)
}, reason= >{
  // When the status of p1 instance is modified to Rejected, the second function is executed; reason is the value of [[PromiseResult]]
  console.log('failure', reason)
});

Copy the code

The following order of code control (executor functions control synchronized code)

  • new PromiseConstructor execution
  • performexecutorFunction:
    • The output1
    • Modify status and values immediately, and notify basedTHENThe injected method executes at this time.THENMethod has not been executed, method has not been injected, do not know who will execute the notification, so at this time, you need to save the operation performed by the notification method and put it into the waiting task queue. This operation itself is asynchronous, and you need to wait for method injection to complete before notifying its execution
    • The output2(to theexecutorThe function has been executed.
  • Execution instance.then(result, reason)Inject two methods, and the injected methods are saved (they are not executed at this point)
  • The input 3
  • Prior notice based on.then()The first of the two injected methods executes (resultMethods)
let p1 = new Promise((resolve, reject) = >{
    console.log('1');/ / 1
    resolve('OK');
    console.log('2');
});

p1.then(result= >{
    console.log('Success:'+result);
}, reason= >{
    console.log('Failure:'+reason);
});
console.log('3');
Copy the code

new PriomiseThe internal mechanism

  1. new PromiseThe delivery will be executed immediatelyexecutorfunction
  2. inexecutorFunction is used to control an asynchronous operation.
  3. And passed on toexecutorThe function takes two arguments:Resolve, reject, and both arguments are functions
  4. createPromiseClassp1, each onePromiseEach instance of the
    • [[PromiseState]] promiseStatus:
      • pending: Ready
      • fulfilled(Older browsers)/resolved(New version browser): Success status (cashed)
      • rejected: Failed state (rejected)
      • Once the state changes frompendingChange forfulfilledOr is itrejectedCan’t change its state again
    • [[PromiseResult]] promise
      • The default isundefined, generally stores the result of success or the cause of failure
      • eachPromiseInstance toPromiseThe prototype of the classp1.__proto__ = Promise.prototype
      • PromiseThe method on the prototype:then/catch/finally
      • ifexecutorIf code execution in a function fails, the instance status changes to failed, and[[PromiseResult]]Is the cause of the error

Take a look at the following code example

A new Promise must be passed in a function (executor function) or an error will be reported

let p1 = new Promise(a);console.log(p1);Resolver undefined is not a function at new Promise
Copy the code

The new Promise will immediately execute the passed executor function, and the resolve control instance will change to a successful state, passing the value 100 as a result of success

[[PromiseState]]: 'fufilled' [[PromiseResult]]: 100

let p1 = new Promise(function (resolve, reject) { 
  resolve(100);
});
p1.then();
Copy the code

Reject controls the state of the instance to fail, passing the value NO, which is the result of the failure

[[PromiseState]]: 'rejected' [[PromiseResult]]: NO

let p1 = new Promise(function (resolve, reject) { 
  reject('NO');
});
p1.then();
Copy the code

THENmethods

If the current instance status is successful or failed, create an asynchronous microtask and wait for the synchronization task to end. Then determine which method to execute based on the success or failure

  • If the state is stillpending, the method can be stored directly without creating asynchronous microtasks
  • If the state has changed(fulfilled/rejected), then executeresolve/rejectAn asynchronous microtask will be created and executed based on the status after the synchronization task is completed.thenDynamically stored functions

See the chestnuts

let p1 = new Promise(resolve= > {
    // After 1000ms, the timer starts, and the two methods in p1.then() have been injected
    setTimeout(function(){
        // Execute resolve to immediately change the promise state and value
        resolve('OK); console.log(1); }, 1000)}); p1.then(result=>{ console.log(2); }); // The final result is 1, 2Copy the code
  • The output1 2
    • instructionsthenThe method is asynchronous: executeresolveAfter, do not wait for executionthenIn the methodresultInstead, put it in an event queue and output the synchronized code first 1Find asynchronous code in the event queue to execute the output 2

Conclusion: Whether based on or notTHENInjected method, executeresolve/reject“, “Modify state and value” is synchronous and will be processed immediately, but “notify corresponding injection method execution” is asynchronous operation, will not be processed immediately, just put it in the waiting task queue, when other things are finished, return again, notify corresponding injection method execution

.then()It is performed in two cases

  1. .then(onfulfilled, onrejected)Returns a newPromiseInstance, whose success or failure depends on:onfulfilled/onrejectedExecution whether an error is reported and results are returned (regardless of executiononfulfilledoronrejected, the new instance is returned as a success as long as the execution does not return an error,[[PromiseResult]]Is the result returned to the instance.
let p1 = new Promise((resolve, reject) = >{
  setTimeout(() = >{
    <!-- resolve('OK'); -- > <! -- reject('OK'); -->
  }, 1000);
});

let p2 = p1.then(result= >{
  console.log('success', result);
  return 10;
}, reason= >{
  console.log('failure', reason);
  return 0;
})
console.log(p2);

Copy the code

Perform the resolve (” OK “); P2 is a new promise instance, which will be fulfilled with [[PromiseState]]. [[PromiseResult]] to 10

Perform reject (‘ NO ‘); P2 is a new promise instance, which will be fulfilled with [[PromiseState]]. [[PromiseResult]] to 0

  1. thenThe method returns a brand new Promise instance, and the success or failure of that instance depends on things like thatp2Success and failure
let p1 = new Promise((resolve, reject) = >{
  setTimeout(() = >{
    resolve('OK'); <! -- reject('OK'); -->
  }, 1000);
});

let p2 = p1.then(result= >{
  console.log('success', result);
  return new Promise((resolve, reject) = >{
    <!-- reject('New instance'); -->
    resolve('New instance'); })},reason= >{
  console.log('failure', reason);
  return 0;
})
Copy the code

If the.then method returns a new promise instance (promise2), then the result of p2 is the same as the result of the return

Reject (‘ new instance ‘); console.log(p2); P2 is a new promise instance whose [[PromiseState]] is Rejected; [[PromiseResult]] = ‘new instance’

Execute resolve(‘ new instance ‘); console.log(p2); P2 is a new promise instance, which will be fulfilled with [[PromiseState]]. [[PromiseResult]] = ‘new instance’

Promise. Resolve /reject: directly returns the specified state of the Promise instance Promise. All: depends on whether multiple Promise instances have failed

async await

Definition of async function: an async function is a function declared using the async keyword.

Async functions are instances of AsyncFunction constructors and allow the await keyword.

The async and await keywords allow us to write asynchronous behavior based on promises in a more concise way, without having to deliberately chain call promises.

Async functions can also be defined as expressions.

Async functions may contain zero or more await expressions.

Async await “new in ES7” async: decorates a function and returns a promise instance by default. The advantage of returning a Promise instance is that a normal function is executed, and the result of the execution is controlled by Promise by default. Then methods can be called to handle the logic, and chain calls can be implemented

Async must return a Promise object. If the return value of an async function does not appear to be a promise, it will be wrapped implicitly in a Promise.

async function fn() {
  return 10;
}
console.log(fn());
Copy the code

Is equivalent to

async function fn() {
  return Promise.resolve(10);
}
Copy the code

[[PromiseState]]: ‘depressing ‘, [[PromiseResult]]: ’10’

async function fn() {
  if(true) throw new TypeError('11');
}
console.log(fn());
Copy the code

Return a Promise instance, [[PromiseState]]: ‘Rejected ‘, [[PromiseResult]]: TypeError ’11’

async function fn() {
  setTimeout(() = >{
    return 10;
  }, 1000)}console.log(fn());
Copy the code

[[PromiseState]]: ‘depressing ‘, [[PromiseResult]]: undefined

Then look at chestnuts

  • The first line of code up to (and including) the first await expression (if any) is run synchronously
  • An async function must be executed asynchronously if the function body has an await expression.
async function foo() {
   await 1
}
Copy the code

Is equivalent to

function foo() {
   return Promise.resolve(1).then(() = > undefined)}Copy the code

Conclusion: Asynchronous operations cannot be controlled, but are only used to decorate the function so that it returns a Promise instance and can call the.then method. Whether execute resolve or reject, as long as the code does not report errors, it will be successful, and [[PromiseState]] will be fulfilled. [[PromsieResult]] is the result of a return

await

awaitThe operator is used to wait for aPromiseObject. It can only be done in asynchronous functionsasync functionThe use of.

Definition of await: Await expression suspends execution of the current async function until the Promise processing completes. If the Promise is fulfilled normally, the resolve function parameter of its callback will be the value of the await expression and the async function will continue to be executed.

Scope of use: the await keyword is valid only within async functions. If you use async outside the async function body, a SyntaxError will be raised.

The purpose of async/await is to simplify the syntax needed to use a Promise based API. Async /await behaves as if a generator and promise are used together.

Await execution order: an await expression suspends the execution of an entire async function and gives it control, resuming the process only after the promise-based asynchronous operation it is waiting for has been fulfilled or rejected. The resolve value of the promise is treated as the return value of the await expression. Use the async/await keyword to use normal try/catch blocks in asynchronous code.

Await: normally await is followed by a promise instance. If a promise instance is not set, the value itself is returned.

The return value of await is in two cases:

  • Case one: normal valuesawait 10, it returns one by defaultpromiseThe instance is successful by defaultreturnThe value behind the
  • The second case: function executionawait fn()
    1. Execute immediatelyfn()Function to receive the return value of the function
    2. judgeawaitReturn value ispromsieThe instance
    3. If not, analyze according to the above two situations

The expression following an EG ↓ await is an instance of a Promise

  1. PromiseIf the process is normal, the status is(pending -> fulfilled), the callbackresolveFunction parameter asawaitThe value of the expression continues execution async function
async function fn() {
  let result = await new Promise((resolve, reject) = >{
    setTimeout(() = >{
      resolve(10);
    }, 1000)});console.log(result);
}

console.log(fn());
Copy the code

Perform fn (); Output: 10 output after 1000ms

  1. PromiseHandle exceptions( pending -> rejected ).awaitThe expression will takePromiseThe exception cause is thrown
let p1 = new Promise((resolve, reject) = >{
  reject('2');
})

async function f1() { 
  let result = await p1;
  console.log(result);
}
f1(); 
Copy the code

The output

  Uncaught (in promise) 2
Copy the code

The expression after await is not a Promise instance

  1. The first case:awaitThe following expression is the base value
Async function fn() {// equivalent to let result = await promise.resolve (10); let result = await 10; console.log(result); } fn();Copy the code

10 Run console.log(fn()). Output a Promise instance. “Confirm: Async will default to a function returning a Promise instance.”

  1. The second case:awaitThe latter expression is a function
function func() { 
  return new Promise(resolve= >{
    resolve(2); })};async function fn() { 
  let result = await func();
  console.log(result);
};

fn();
Copy the code

The output

2
Copy the code

The expression after await is a function func in the order of execution:

  • Executed immediatelyfunc()The function,awaitTo receive thefunc()The return value of the
  • awaitThe following expression is one promiseInstance, andpromise The status offulfilled, is called backresolveThe function argument isawaitValue of an expression; That is let result = await 2;
  • Continue to performasync function
  • The outputresultA value of2

“Await” is an asynchronous microtask. Store all the code to be executed under “await” in the current context into the asynchronous microtask. After the promise instance behind “await” becomes successful, the following code (i.e. the asynchronous microtask) will be executed.

Comprehensive EG

function func() { 
  console.log(1); 
  return new Promise(resolve= >{
    setTimeout(() = >{
      resolve(2);
    }, 1000)})};console.log(3); 

async function fn() { 
  console.log(4);
  let result = await func();

  console.log(result);
  console.log(5);
};

fn(); 
console.log(6);
Copy the code

Order of execution:

  • The browser executes from top to bottom, first executing synchronized code in the global context, with output:3
  • Executive functionfn().asyncInside the function, from the first line of code to the first oneawaitExpressions are run synchronously. Output:4
  • awaitThe code after the expression can be thought of as having a chained callthenIn the callback, that is, put the current contextawaitThe code to be executed below is stored in an asynchronous microtask as a whole, whenawait At the back of the promiseAfter the instance status is successful, execute the following code. At this point,EventQueueThere is a task in the micro task queue.func()Synchronized code in the function body, output:1
  • func()The result returned is an asynchronous macro task placed inEventQueueIn the macro task queue.
  • The browser doesn’t wait, it just keeps executing. Output:6
  • When the synchronization code is complete, the browser executesEventqueueTo see if there are any executable tasks in the microtask queue
  • At this point,[[PromiseState]]The status ofpending, so a microtask is an unexecutable task.
  • So let’s go to the macro task queue and go1000ms performresolve(2), execution completed,[[PromiseState]]State frompendingintofulfilledThe macro task is complete.
  • The browser continues to look for executable code in the microtask queue,promiseStatus becomes successful,awaitAfter the code can execute, the code in the microtask queue executes, output:2, 5
  • ifEventQueue If no task exists, the execution ends. Final output:3, 4, 1, 6, 2, 5

The code after the await expression can be considered to exist in the then callback of the chained call. Multiple await expressions will be added to the then callback of the chained call, and the return value will be the return value of the last THEN callback.

Note: The Promise chain is constructed in stages, so care must be taken with error functions when dealing with asynchronous functions. Typically we configure a. Catch handler on the promise chain to catch all errors

If no exception handling is done for a failed Promise instance, the console throws an exception without affecting subsequent code execution

async function fn() {
  let result = await Promise.reject(1);
  console.log(result);
  setTimeout(() = >{
    console.log('Timer 1')
  })
}
fn();
setTimeout(() = >{
  console.log('Timer 2')})Copy the code

The code after await is not executed, but does not affect the subsequent code execution, output

Uncaught (in promise) 1The timer2
Copy the code

Promise.catch (reason=>{}) async await: try{… }catch(err){.. }

If you handle an exception directly, await receives promise.reject (1), and if.catch() is called, a new Promise instance will be returned that is not intended

let result = await Promise.reject(1).catch();
Copy the code

This method will report an error

let i = 0;
function fn() { 
  console.log(++i);
  fn();
}

fn();// Maximum call stack size exceeded
Copy the code

No errors will be reported, but an endless loop will be formed. In EventLoop, asynchronous tasks are executed only when the main thread is idle. Each call to await will form an asynchronous microtask. This involves switching between two queues to synchronous asynchro, so the browser will not report an error

let i = 0;
async function fn() {
  console.log(++i);
  await Promise.resolve('OK');
  fn();
}
fn();
Copy the code