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
Promise
define
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
Promise
describe
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 a
Promise
The instance- In this instance
可迭代
All within the parameterspromise
Do”(resolved)
“Or not included in the parameterpromise
When the callback is complete(resolve)
;Promise.all
The returnedpromise
asynchronousThe earth becomes complete. - If the parameter
promise
There is a failure(rejected)
, this instance callback failed(reject)
The cause of failure is the first failurepromise
Results. - The iterable passed in is empty,
Promise.all
会synchronousTo return a completed(resolved)
The state of thepromise
. Look at the following example
- In this instance
Promise.any()
- grammar:
Promise.any(iterable);
- Argument: an iterable object
- The return value: Just one of them
promise
If it succeeds, return the one that has succeededpromise
Promise.race()
- grammar:
Promise.race(iterable);
- Argument: an iterable object
- The return value: Returns a
promise
, once one of the iteratorspromise
Resolved or rejected, returnedpromise
It 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 as
reason
的promise
The instance
Promise.resolve()
- grammar:
Promise.reject(value);
- parameter:
Promise
Object resolution argument, which can also be onePromise
Object, or athenable
- The return value: returns a parsed object with the given value
Promise
Object if the argument itself is onePromise
Object, returns this directlyPromise
Object.
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 aPromise
And handle the rejection
Promise.prototype.finally()
- describe: Returns a
Promise
. inpromise
At the end of the day, whatever the result isfulfilled
Or is itrejected
Executes the specified callback function - grammar:
p.finally(onFinally);
Of (function() {// return state (resolved or rejected)});
- parameter:
Promise
Called after the endFunction
. - The return value: Returns a setting
finally
Of the callback functionPromise
Object.
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 setting
finally
Of the callback functionPromise
Object.
Promise
The three concepts of
executor
function
new Promise
Will be executed immediatelyexecutor
Function,executor
Function manages an asynchronous programming code (as does synchronous code)OK
At this timePromise
The state ispending
; By executing when our asynchronous operation succeeds or failsresolve
orreject
Function, which effectively changes the instance state to a successful or failed state, i.e. frompending
intoThis is a big pity/Rejected (fail).
; If the code error case, also change the state toRejected (failure)
;
- The instance
- Each Promise instance has it
[[PromiseState]]
and[[PromiseResult]]
Method,[[PromiseState]]
ispromise
Status:pending
,fulfilled/resolve
,rejected
Three states;[[PromiseResult]]
ispromise
Value: The default value isundefined
, generally stores the result of success or the cause of failure.
Promise
The prototype approach.then()
: Used to control successful or failed operations
- Instances can call
.then()
It stores two methods:result
和reason
(both functions); whenp1
The instance status is changed tofulfilled
Is the first function that the notification passes(result)
To perform,result
is[[PromiseResult]]
The value of the; whenp1
The instance status is changed torejected
The second function of the notification pass(reason)
To perform,reason
is[[PromiseResult]]
The value of the - Whether or not based on
THEN
Injected 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)
: performthen
The method is simply to takeonfulfilled/onrejected
The function is saved (the saved operation is synchronous), but the function has not yet been executed, whenpromise
When the status changes to success or failure, the corresponding function will be triggered to execute,then
Is an asynchronous microtask
Promsie
How is asynchronous programming controlled
new Promise
The created instance, its status and results, depend on:executor
In the functionresolve/reject
performexecutor
Whether an error is reported during function execution
- perform
.then
Method returns a brand newpromise
The instance
new Promise
“To create onepromise
Instance, at this time inexecutor
Function to manage a set of asynchronous code- If the asynchronous operation succeeds or fails, perform it
resolve/reject
In order to controlpromise
The state and results of the instance - Based on status and results, you can control based
.then
Which of the two injected methods is executed
Watching the chestnuts
- The order in which the following code is executed (
executor
Functions govern asynchronous programming)new Promise
Constructor execution- perform
executor
Function: 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 the
1000ms
- Execute timer callback function: by executing
resolve
changepromise
Status 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 Promise
Constructor execution- perform
executor
Function:- The output
1
- Modify status and values immediately, and notify based
THEN
The injected method executes at this time.THEN
Method 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 output
2
(to theexecutor
The function has been executed.
- The output
- 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 (result
Methods)
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 Priomise
The internal mechanism
new Promise
The delivery will be executed immediatelyexecutor
function- in
executor
Function is used to control an asynchronous operation. - And passed on to
executor
The function takes two arguments:Resolve, reject
, and both arguments are functions - create
Promise
Classp1
, each onePromise
Each instance of the[[PromiseState]] promise
Status:pending
: Readyfulfilled
(Older browsers)/resolved
(New version browser): Success status (cashed)rejected
: Failed state (rejected)- Once the state changes from
pending
Change forfulfilled
Or is itrejected
Can’t change its state again
[[PromiseResult]] promise
值- The default is
undefined
, generally stores the result of success or the cause of failure - each
Promise
Instance toPromise
The prototype of the classp1.__proto__ = Promise.prototype
Promise
The method on the prototype:then/catch/finally
- if
executor
If code execution in a function fails, the instance status changes to failed, and[[PromiseResult]]
Is the cause of the error
- The default is
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
THEN
methods
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 still
pending
, the method can be stored directly without creating asynchronous microtasks - If the state has changed
(fulfilled/rejected)
, then executeresolve/reject
An asynchronous microtask will be created and executed based on the status after the synchronization task is completed.then
Dynamically 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 output
1 2
- instructions
then
The method is asynchronous: executeresolve
After, do not wait for executionthen
In the methodresult
Instead, put it in an event queue and output the synchronized code first1
Find asynchronous code in the event queue to execute the output2
- instructions
Conclusion: Whether based on or notTHEN
Injected 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
.then(onfulfilled, onrejected)
Returns a newPromise
Instance, whose success or failure depends on:onfulfilled/onrejected
Execution whether an error is reported and results are returned (regardless of executiononfulfilled
oronrejected
, 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
then
The method returns a brand new Promise instance, and the success or failure of that instance depends on things like thatp2
Success 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
await
The operator is used to wait for aPromise
Object. It can only be done in asynchronous functionsasync function
The 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 values
await 10
, it returns one by defaultpromise
The instance is successful by defaultreturn
The value behind the - The second case: function execution
await fn()
- Execute immediately
fn()
Function to receive the return value of the function - judge
await
Return value ispromsie
The instance - If not, analyze according to the above two situations
- Execute immediately
The expression following an EG ↓ await is an instance of a Promise
Promise
If the process is normal, the status is(pending -> fulfilled)
, the callbackresolve
Function parameter asawait
The value of the expression continues executionasync 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
Promise
Handle exceptions( pending -> rejected )
.await
The expression will takePromise
The 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
- The first case:
await
The 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.”
- The second case:
await
The 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 immediately
func()
The function,await
To receive thefunc()
The return value of the await
The following expression is onepromise
Instance, andpromise
The status offulfilled
, is called backresolve
The function argument isawait
Value of an expression; That islet result = await 2
;- Continue to perform
async function
- The output
result
A 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 function
fn()
.async
Inside the function, from the first line of code to the first oneawait
Expressions are run synchronously. Output:4
await
The code after the expression can be thought of as having a chained callthen
In the callback, that is, put the current contextawait
The code to be executed below is stored in an asynchronous microtask as a whole, whenawait
At the back of thepromise
After the instance status is successful, execute the following code. At this point,EventQueue
There 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 inEventQueue
In the macro task queue.- The browser doesn’t wait, it just keeps executing. Output:
6
- When the synchronization code is complete, the browser executes
Eventqueue
To 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 go
1000ms
performresolve(2)
, execution completed,[[PromiseState]]
State frompending
intofulfilled
The macro task is complete. - The browser continues to look for executable code in the microtask queue,
promise
Status becomes successful,await
After the code can execute, the code in the microtask queue executes, output:2, 5
- if
EventQueue
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