The
async function
declaration defines an asynchronous function, which returns an AsyncFunction
object. An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise
to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.
You can also define async functions using an async function expression.
Syntax
async function name([param[, param[, ... param]]]) { statements }
Parameters
name
- The function name.
param
- The name of an argument to be passed to the function.
statements
- The statements comprising the body of the function.
Return value
A
Promise
which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.Description
An
Remember, the
async
function can contain an await
expression that pauses the execution of the async function and waits for the passed Promise
's resolution, and then resumes the async
function's execution and returns the resolved value.Remember, the
await
keyword is only valid inside async
functions. If you use it outside of an async
function's body, you will get a SyntaxError
.Examples
Simple example
var resolveAfter2Seconds = function() {
console.log("starting slow promise");
return new Promise(resolve => {
setTimeout(function() {
resolve(20);
console.log("slow promise is done");
}, 2000);
});
};
var resolveAfter1Second = function() {
console.log("starting fast promise");
return new Promise(resolve => {
setTimeout(function() {
resolve(10);
console.log("fast promise is done");
}, 1000);
});
};
var sequentialStart = async function() {
console.log('==SEQUENTIAL START==');
// If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.
const slow = await resolveAfter2Seconds();
const fast = await resolveAfter1Second();
console.log(slow);
console.log(fast);
}
var concurrentStart = async function() {
console.log('==CONCURRENT START with await==');
const slow = resolveAfter2Seconds(); // starts timer immediately
const fast = resolveAfter1Second();
console.log(await slow);
console.log(await fast); // waits for slow to finish, even though fast is already done!
}
var stillConcurrent = function() {
console.log('==CONCURRENT START with Promise.all==');
Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => {
console.log(messages[0]); // slow
console.log(messages[1]); // fast
});
}
var parallel = function() {
console.log('==PARALLEL with Promise.then==');
resolveAfter2Seconds().then((message)=>console.log(message));
resolveAfter1Second().then((message)=>console.log(message));
}
sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast"
// wait above to finish
setTimeout(concurrentStart, 4000); // after 2 seconds, logs "slow" and then "fast"
// wait again
setTimeout(stillConcurrent, 7000); // same as concurrentStart
// wait again
setTimeout(parallel, 10000); // trully parallel: after 1 second, logs "fast", then after 1 more second, "slow"
Rewriting a promise chain with an async
function
An API that returns a
Promise
will result in a promise chain, and it splits the function into many parts. Consider the following code:function getProcessedData(url) {
return downloadData(url) // returns a promise
.catch(e => {
return downloadFallbackData(url) // returns a promise
})
.then(v => {
return processDataInWorker(v); // returns a promise
});
}
it can be rewritten with a single
async
function as follows:async function getProcessedData(url) {
let v;
try {
v = await downloadData(url);
} catch(e) {
v = await downloadFallbackData(url);
}
return processDataInWorker(v);
}
Note that in the above example, there is no
await
statement on the return
statement, because the return value of an async function
is implicitly wrapped in Promise.resolve
.
No comments:
Post a Comment