A deep dive into async functions in JavaScript
async function
The return value of the async function is the promise object, and the result of the promise object is determined by the return value of the async function execution. The async function can make asynchronous operations more convenient. In short, it is the syntactic sugar of Generator.
Define async function, the characteristic is that even if the internal return result of the function is not a promise object, the final return result of calling the function is still a promise object , the code is as follows: If the returned result is not a Promise object:
<script> async function fn(){ // 返回的结果是字符串 // return '123' // // 返回的结果是undefined // return; // 返回的结果是抛出一个异常 throw new 'error' } const result = fn() console.log(result); </script>
If the returned result is a Promise object When, we can use the then method normally, as follows:
<script> async function fn(){ return new Promise((resolve,reject)=>{ // resolve('成功的数据') reject('失败的数据') }) } const result = fn() // 调用 then 方法 result.then((value)=>{ console.log(value); },(reason)=>{ console.log(reason); // 打印失败的数据 }) </script>
Through the above introduction to async, I feel that its function is a bit tasteless, but in fact it is No, but async needs to be used together with await to achieve the effect of syntactic sugar.
Characteristics of await: await must be written in the async function
The expression on the right side of await Generally, it is a promise object
await returns the value of successful promise
If the promise of await fails, an exception will be thrown and needs to be captured and processed through try...catch
To put it bluntly: await is equivalent to the first callback function of the then method, only returning successful values, and failed values need to be captured by try...catch. An error is thrown inside the async function, which will cause the returned Promise object to become rejected. The thrown error object will be received by the catch method callback function.
<script> const p = new Promise((resolve,reject)=>{ // resolve('用户数据') reject('用户加载数据失败了') }) async function fn(){ // 为防止promise是失败的状态,加上try...catch进行异常捕获 try { // await 返回的结果就是 promise 返回成功的值 let result = await p console.log(result); } catch (error) { console.log(error);//因为是失败的状态,所以打印:用户加载数据失败了 } } fn() </script>
async uses the formSummary:
(1)Promise behind the await command Object, the operation result may be rejected, so it is best to put the await command in the try...catch code block.
(2)If there are asynchronous operations behind multiple await commands, and if there is no subsequent relationship, it is best to let them trigger at the same time. For example: await Promise.all([a(), b()]), here is a brief mention
(3)await The command can only be used in async functions. If used in ordinary functions, an error will be reported.
(4)(Understand the operating principle of async) The async function can retain the running stack. When running an asynchronous task inside the ordinary function , if the asynchronous task ends, the ordinary function may have finished running long ago, and the context of the asynchronous task has disappeared. If the asynchronous task reports an error, the error stack will not include the ordinary function; while the asynchronous task inside the async function is running, the async function is paused executed, so once the asynchronous task inside the async function runs and an error is reported, the error stack will include the async function.
// 函数声明
async function foo() {}
// 函数表达式
const foo = async function () {};
// 对象的方法
let obj = { async foo() {} };
obj.foo().then(...)
// Class 的方法
class Storage {
constructor() {
this.cachePromise = caches.open('avatars');
}
async getAvatar(name) {
const cache = await this.cachePromise;
return cache.match(`/avatars/${name}.jpg`);
}
}
const storage = new Storage();
storage.getAvatar('jake').then(…);
// 箭头函数
const foo = async () => {};
Copy after login
async reads the file// 函数声明 async function foo() {} // 函数表达式 const foo = async function () {}; // 对象的方法 let obj = { async foo() {} }; obj.foo().then(...) // Class 的方法 class Storage { constructor() { this.cachePromise = caches.open('avatars'); } async getAvatar(name) { const cache = await this.cachePromise; return cache.match(`/avatars/${name}.jpg`); } } const storage = new Storage(); storage.getAvatar('jake').then(…); // 箭头函数 const foo = async () => {};
And the promise explained before reads the file content Similarly, we can also use async to read files. The code is as follows:
// 1.引入 fs 模块 const fs = require('fs') // 2.读取文件 function index(){ return new Promise((resolve,reject)=>{ fs.readFile('./index.md',(err,data)=>{ // 如果失败 if(err) reject(err) // 如果成功 resolve(data) }) }) } function index1(){ return new Promise((resolve,reject)=>{ fs.readFile('./index1.md',(err,data)=>{ // 如果失败 if(err) reject(err) // 如果成功 resolve(data) }) }) } function index2(){ return new Promise((resolve,reject)=>{ fs.readFile('./index2.md',(err,data)=>{ // 如果失败 if(err) reject(err) // 如果成功 resolve(data) }) }) } // 3.声明一个 async 函数 async function fn(){ let i = await index() let i1 = await index1() let i2 = await index2() console.log(i.toString()); console.log(i1.toString()); console.log(i2.toString()); } fn()
and before Explain
promise sending ajax request Similarly, we can also use async to send ajax request. The code is as follows: <script>
// 发送 AJAX请求,返回的结果是 Promise 对象
function sendAjax(url){
return new Promise((resolve,reject)=>{
// 创建对象
const x = new XMLHttpRequest()
// 初始化
x.open('GET',url)
// 发送
x.send()
// 事件绑定
x.onreadystatechange = function(){
if(x.readyState === 4){
if(x.status >= 200 && x.status < 300){
// 如果响应成功
resolve(x.response)
// 如果响应失败
reject(x.status)
}
}
}
})
}
// promise then 方法测试
// const result = sendAjax("https://ai.baidu.com/").then(value=>{
// console.log(value);
// },reason=>{})
// async 与 await 测试
async function fn(){
// 发送 AJAX 请求
let result = await sendAjax("https://ai.baidu.com/")
console.log(result);
}
fn()
</script>
, we found that the relationship between async and await is very similar to the relationship between Generator and yield. Friends who are not familiar with Generator can read my previous article:
Generator Explanation; After comparison, we found that: async function is to replace the asterisk (*) of the Generator function with async, and replace yield with await. The code comparison is as follows: <script>
// Generator 函数
function * person() {
console.log('hello world');
yield '第一分隔线'
console.log('hello world 1');
yield '第二分隔线'
console.log('hello world 2');
yield '第三分隔线'
}
let iterator = person()
// console.log(iterator); 打印的就是一个迭代器对象,里面有一个 next() 方法,我们借助next方法让它运行
iterator.next()
iterator.next()
iterator.next()
// async函数
const person1 = async function (){
console.log('hello world');
await '第一分隔线'
console.log('hello world 1');
await '第二分隔线'
console.log('hello world 2');
await '第三分隔线'
}
person1()
</script>
The implementation principle of the async function is to wrap the Generator function and the automatic executor in a function.
<script> async function fn(args) {} // 等同于 function fn(args) { // spawn函数就是自动执行器 return spawn(function* () {}); } </script>
We can analyze the writing characteristics and style of Generator and async code:
<script> // Generator 函数 function Generator(a, b) { return spawn(function*() { let r = null; try { for(let k of b) { r = yield k(a); } } catch(e) { /* 忽略错误,继续执行 */ } return r; }); } // async 函数 async function async(a, b) { let r = null; try { for(let k of b) { r = await k(a); } } catch(e) { /* 忽略错误,继续执行 */ } return r; } </script>
所以 async 函数的实现符合语义也很简洁,不用写Generator的自动执行器,改在语言底层提供,因此代码量少。
从上文代码我们可以总结以下几点:
(1)Generator函数执行需要借助执行器,而async函数自带执行器,即async不需要像生成器一样需要借助 next 方法才能执行,而是会自动执行。
(2)相比于生成器函数,我们可以看到 async 函数的语义更加清晰
(3)上面就说了,async函数可以接受Promise或者其他原始类型,而生成器函数yield命令后面只能是Promise对象或者Thunk函数。
(4)async函数返回值只能是Promise对象,而生成器函数返回值是 Iterator 对象
【推荐学习:javascript高级教程】
The above is the detailed content of A deep dive into async functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
