Home >Web Front-end >JS Tutorial >About JavaScript asynchronous calling methods
You can modify the following aa()
function, the purpose is to use console.log()
to output the want-value after one second
function aa() { setTimeout(function() { return "want-value"; }, 1000); }
However, there are additional requirements:
##aa() The function can be modified at will, but there cannot be a
console. log()
console.log() There cannot be a
setTimeout package in the statement
##setTimeout()
Often used to simulate asynchronous operations. At first, asynchronous used callbacks to notify (call) the handler of the processing results.function aa(callback) { setTimeout(function() { if (typeof callback === "function") { callback("want-value"); } }, 1000); } aa(function(v) { console.log(v); });
However, when callbacks are used in larger asynchronous applications, they are prone to multi-layer nesting, so some methods have been proposed later. For "flattening", this part can refer to the "flattening" of chat asynchronous calls. Of course Promise is a very popular method and was eventually adopted by ES6. Use Promise to implement it as follows:
function aa() { return new Promise(resolve => { setTimeout(function() { resolve("want-value"); }, 1000); }); } aa().then(v => console.log(v));As far as this example is concerned, it is similar to the previous callback example. However, it will lead to a more recommended method currently - async/await, which is supported starting from ES2017:
function aa() { return new Promise(resolve => { setTimeout(function() { resolve("want-value"); }, 1000); }); } async function main() { const v = await aa(); console.log(v); } main();
aa()
The definition is the same as the definition in the Promise method, But when calling,await is used to wait asynchronously. After waiting for the asynchronous result, use
console.log() to process it.
It should be noted here that
await
async method, so in order to use
await you must define an
async's main method and called in the global scope. Since the main method is asynchronous (declared as async), if there are other statements after
main() is called, such as
console.log("hello"), then this sentence will be executed first.
async/await syntax makes writing asynchronous calls like writing synchronous code. When writing code, you can avoid logical jumps and write it more easily. (Reference: From hell to heaven, Node callback changes to async/await)
main()
and then callmain() You can use IIFE for this part Encapsulate it,
(async () => { const v = await aa(); console.log(v); })();
The above is the detailed content of About JavaScript asynchronous calling methods. For more information, please follow other related articles on the PHP Chinese website!