“This is the 12th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
This is the article I prepared for the Promise series
JS Promise Literacy and quick Start “up” – Nuggets (juejin. Cn)
JS Promise Literacy and quick Start “In” – Nuggets (juejin. Cn)
JS Promise Literacy and Quick Start – Nuggets (juejin. Cn)
Optimization of sample
We have promises to do asynchronous callback processing, but we need to use a processing template: the callback function has to be handled in the THEN function
Among the new ES8 features, ayNC /await lets me write asynchronous code synchronously. For example, if a Promise is executed and returns a value of n, we need to use this return value for the callback, as follows:
let p = new Promise((resolve, reject) = > {
fetch(url).then(d= >resolve(d));
}).then(data= > do(data))
Copy the code
If we wrote it using asynchronous functions, the code would look like this:
let p = await fetch(url);
Copy the code
The above shows the effect of optimizing the Promise with await. Now, talk about them in detail
async
Defining asynchronous functions
In normal function declaration mode, add before the function keyword as an example:
async function test(){}
Copy the code
This declares test to be an asynchronous function
use
Asynchronous functions and ordinary functions use the same method, directly called
test()
Copy the code
After the test call, the internal function code block executes normally, for example
async function test(){
console.log(2)}console.log(1)
test()
console.log(3)
// -> 1, 2, 3
Copy the code
However, if an asynchronous operation is involved in test, such as a classic setTimeout call, the asynchronous part of the call will be pushed to the microtask queue, and the rest will be executed normally.
However, if we need to wait, after setTimeout (which stands for asynchronous function) is completed, we need to add await keyword constraint to setTimeout (asynchronous function), and then the test execution will be suspended, waiting for the external synchronous code to complete. Back to the code:
This code has embedded async, await, promise, setTimeout, etc. Its output indicates the code execution order
We are now at the base of this code, adding the keyword await while we are executing delay() and making the following code wait for the result
This changes the order of execution of the code a bit
The return value
Async defines an asynchronous function that implicitly wraps the result into a Prmise. Resolve object for return
If an exception occurs in an asynchronous function, such as an exception thrown with the throw keyword, the function returns a promise.reject object
await
Represents waiting for a return value from an asynchronous function and unpacking the Promise object
Resolve (1) : let a = promise.resolve (1) : let a = promise.resolve (1) : let a = promise.resolve (1)
let a = await Promise.resolve(1);
console.log(a)
/ / - > 1
Copy the code