Talking about Async/Await
Handling asynchronous with async/await
async: Declare an asynchronous function (async function someName(){...})
Promise, the return value is also aPromiseObjectasyncThe asynchronous operation inside the function is executed before it is executed.thenThe callback function specified by the method;await。await: suspending asynchronous function execution (var result = await someAsyncCall())
PromiseBefore calling,awaitForce other code to wait untilPromiseComplete and return the result;PromiseUsed together, not for use with callbacks;asyncThe function is used internally.awaitThe back needs to be aPromiseObject, if not, will be converted intoPromiseObjectPromiseObject becomesrejectState, then the wholeasyncThe function will interrupt the operation;resolve, then the return value will becomethenThe parameters inside.async function f() {
return await 123
}
f().then(v => {
console.log(v) // 123
})
How to be fault tolerant? due toawaitBackpromiseThe result of the operation may berejectedBest to putawaitput into atry {} catch {}in.
awaitAfter the asynchronous operation, if there is no dependency on each other, it is best to trigger at the same time, which will be introduced in the following scenario.
awaitOnly inasyncAmong the functions, if you are in a normal function, an error will be reported.
async with awaitCompared to direct usePromiseThe advantage is thatthenThe call chain can write the code more clearly and accurately;awaitMay cause performance problems becauseawaitWill block the code, maybe the subsequent asynchronous code does not depend on the former, but still need to wait for the former to complete, causing the code to lose concurrency.var a = 0
var b = async () => {
a = a + await 10
console.log('2', a) // -> '2' 10
a = (await 10) + a
console.log('3', a) // -> '3' 20
}
b()
a++
console.log('1', a) // -> '1' 1
bExecute first, after executionawait 10Previous variablea still is0,Becauseawait Internally implementedgenerators ,generators Will keep things in the stack, so this timea = 0Was savedawait Is asynchronous operation, encounteredawaitWill return immediatelypendingStatefulPromiseThe object temporarily returns control of the execution code, so that the code outside the function can continue to execute, so it will be executed first.console.log('1', a);a = 10;Write a function and let it returnpromiseObject, the function of this function is2sThen multiply the value by2。
// returns double the value after 2s
function doubleAfter2seconds(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2 * num)
}, 2000)
} )
}
Write another nowasyncFunction so that it can be usedawaitKeyword,awaitPlaced behind is returningpromiseAn expression of the object, so it can be written laterdoubleAfter2seconds The call to the function.
async function testResult() {
let result = await doubleAfter2seconds(30)
console.log(result)
}
testResult() // Open the console. After 2s, the output is 60.
Specific to our code, encounteredawaitAfter that, the code is suspended and waitingdoubleAfter2seconds(30)Finished,doubleAfter2seconds(30)returnpromiseStart execution, after 2 seconds,promisecarried outresolve And returned a value60At this timeawaitOnly get the return value60And then assign it toresult, the pause ends, the code begins to execute, executeconsole.logStatement.
We also issue three requests that are not dependent on each other, ifasync/awaitIt seems unwise.
async function getABC() {
let a = await getA() {}
let b = await getB() {}
let c = await getC() {}
return A*B*C
}
Above we need 2s, B needs 4s, C needs 4s, C needs 3s, we send requests as shown above, there is a relationship of mutual dependence, c, etc. b is executed, b, etc. is executed, starting from the beginning to the end (2+3 +4) = 9s.
At this point we need to usePromise.all()Asynchronous calls are executed in parallel, rather than one after another, as follows:
async function getABC() {
let results = await Promise.all([ getValueA, getValueB, getValueC])
return results.reduce((total, value) => total * value)
}
This will save us a lot of time, from the original 9s to 4s, is not very happy, yeah~
Base64ToImage BitmapToBase64...
thought: The topic asks to find all the information of the latest employees. Through a sub-query (select max(hire_date) from employees), find the latest hire time of the employee, hire_date, and then ...
Recently, I am learning mathematical modeling and found a very good course on B station. It is very comprehensive and all the algorithms I often test involve:Qingfeng Mathematical Modeling This articl...
When x = 0 or y = 0 when f [x] [y] = 0 When a [x] = b [y] when f [x] [y] = f [x-1] [y-1] +1 When a [x]! = B [y] when f [x] [y] = max (f [x] [y-1], f [x-1] [y]) Note that the string 1 from the start, b...
I learned the enumeration algorithm in this section. The enumeration method is the nature of the problem itself, and all possible solutions are listed in one by one, and in the process of listed one b...
The interface java.util.Map includes three implementation classes: HashMap, Hashtable, and TreeMap. Of course there are LinkedHashMap, ConcurrentHashMap, WeakHashMap. Map is used to storeKey-value...
Everyday fresh items - project preference Understand the e-commerce Web project development process Project demand analysis Page page Function map Deployment page Project framework Understand the e-co...
The following old method used before installed opencv, after reinstalling the system, reinstalled opencv according to the original method, and the result has always been reported: ImportError: Module ...
Various text files are involved in MBD (model-based design), and the automated processing of text files can greatly improve work efficiency. This article briefly introduces the first step of processin...
1. Log in to Mysql cmd enter mysql -u root -pyoupassword (Input rule After you press Enter, you will be prompted to enter the password. Note that there may or may not be spaces before the user name, b...