The async function returns a Promise object, and callbacks can be added using the then method. When a function executes, it returns as soon as it encounters await, waits for the asynchronous operation to complete, and then executes the following statement in the function body.
Method of use
-
Async means that there are asynchronous operations in a function,
-
Await means that the following expression needs to wait for the result.
Syntax examples
async function name() {
await new Promise((resolve) = > {
setTimeout(function(){
console.log("testAwait");
resolve();
}, 1000);
});
console.log('helloAsync')}Copy the code
I. The result of async function execution is Promise
async function HiAsync() {
return "hi";
}
async function HelloAsync() {
return Promise.resolve('hello')}console.log(HiAsync())
console.log(HelloAsync())
HiAsync().then(res= > {
console.log(res) // 'hi'
})
HelloAsync().then(res= > {
console.log(res) // 'hello'
})
Copy the code
2. Await results (even if nested async)
function getSomething() {
return "a";
}
async function testAsync() {
return new Promise((resolve,reject) = > {
setTimeout(() = > {resolve('b')},3000)})}async function deepAsync() {
let p2 = new Promise((resolve, reject) = > {
setTimeout(() = > { resolve('c')},1000)})return new Promise((resolve, reject) = > {
setTimeout(() = > { resolve(p2) }, 3000)})}async function test() {
const v1 = await getSomething();
console.log('v1',v1)
const v2 = await testAsync();
console.log('v2',v2)
const v3 = await deepAsync();
console.log('v3',v3);
}
test();
Copy the code
Pay attention to the point
Await = ‘await’; await = ‘await’; await = ‘await’; In the catch block.
async function myFunction() {
try {
await somethingThatReturnsAPromise();
} catch (err) {
console.log(err); }}// Another way to write it
async function myFunction() {
await somethingThatReturnsAPromise().catch(function (err){
console.log(err);
});
}
Copy the code
2. Await must be used in async functions
If used in normal functions, an error will be reported. There is also a problem with changing the arguments of forEach to async.
The correct way to write this is to use the for loop
async function dbFuc() {
let docs = [1.2.3];
for (let doc of docs) {
console.log(doc)
}
}
Copy the code