亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
What is async/await
Compare Promise, co, async/await
Use Promise chain
co搭配生成器函數(shù)
async/await
深入async/await
async返回值
async函數(shù)的異常
并行
Home Web Front-end Front-end Q&A Is async for es6 or es7?

Is async for es6 or es7?

Jan 29, 2023 pm 05:36 PM
es6 async await es7 async

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

Is async for es6 or es7?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Front-end asynchronous features proposed in ES7 (ES2017): async, await.

What is async/await

async and await are new contents in ES7. For solutions to asynchronous operations, async/await can be said to be the co module and generation Syntactic sugar for device functions. Solve js asynchronous code with clearer semantics.

async, as the name suggests, means "asynchronous". async is used to declare that a function is asynchronous. And await literally means "waiting", which is used to wait for asynchronous completion.

Async and await have a strict rule. Both cannot be separated from each other. However, await can only be written in the async function.

Students who are familiar with the co module should know that the co module is a module written by Master TJ that uses a generator function to solve asynchronous processes. It can be regarded as the executor of the generator function. Async/await is an upgrade to the co module. It has a built-in generator function executor and no longer relies on the co module. At the same time, async returns Promise.

From the above point of view, whether it is the co module or async/await, Promise is used as the most basic unit. Students who do not know much about Promise can first learn more about Promise.

Compare Promise, co, async/await

Let’s use a simple example to compare the similarities, differences, and trade-offs between the three methods.

We use mongodb's nodejs driver to query the mongodb database as an example. The reason is that mongodb's js driver has implemented returning Promise by default, and we do not need to wrap Promise separately.

Use Promise chain

MongoClient.connect(url + db_name).then(db => {
    return db.collection('blogs');
}).then(coll => {
    return coll.find().toArray();
}).then(blogs => {
    console.log(blogs.length);
}).catch(err => {
    console.log(err);
})

The then() method of Promise can return another Promise or a synchronized value. If a synchronized value is returned, Will be wrapped into a Promise. In the above example, db.collection() will return a synchronized value, that is, a collection object, but it will be wrapped into a Promise and will be transparently passed to the next then() method. The above example uses a Promise chain. First connect to the database MongoClient.connect() returns a Promise, then obtain the database object db in the then() method, and then obtain the coll object and return it. Obtain the coll object in the next then() method, then perform a query, return the query results, and call the then() method layer by layer to form a Promise chain. In this Promise chain, if an exception occurs in any link, it will be caught by the final catch(). It can be said that this code written using Promise chain is more elegant and the process is clearer than calling callback functions layer by layer. First get the database object, then get the collection object, and finally query the data. But there is a not very "elegant" problem here, which is that the object obtained by each then() method is the data returned by the previous then() method. It cannot be accessed across layers. What does it mean, that is, in the third then (blogs => {}), we can only get the query result blogs, but cannot use the above db object and coll object. At this time, what if you want to close the database db.close() after printing out the blogs list? At this time, there are two solutions:

The first is to use then() nesting. We break the Promise chain and make it nested, just like using the nesting of callback functions:

MongoClient.connect(url + db_name).then(db => {
    let coll = db.collection('blogs');
    coll.find().toArray().then(blogs => {
        console.log(blogs.length);
        db.close();
    }).catch(err => {
        console.log(err);
    });
}).catch(err => {
    console.log(err);
})

Here we nest two Promise, so that in the last query operation, we can call the outside db object. However, this method is not recommended. The reason is simple, we went from one kind of callback function hell to another kind of Promise callback hell.
Moreover, we need to catch the exception of each Promise, because Promise does not form a chain.

Another way is to pass the db in each then() method:

MongoClient.connect(url + db_name).then(db => {
    return {db:db,coll:db.collection('blogs')};
}).then(result => {
    return {db:result.db,blogs:result.coll.find().toArray()};
}).then(result => {
    return result.blogs.then(blogs => {   //注意這里,result.coll.find().toArray()返回的是一個Promise,因此這里需要再解析一層
        return {db:result.db,blogs:blogs}
    })
}).then(result => {
    console.log(result.blogs.length);
    result.db.close();
}).catch(err => {
    console.log(err);
});

In the return of each then() method, we pass the db and its Each time the other results form an object returned. Please note that it is okay if each result is a synchronized value, but if it is a Promise value, each Promise requires an additional layer of parsing.
For example, in the above example, in the {db:result.db,blogs:result.coll.find().toArray()} object returned by the second then() method, blogs is a Promise. In the next then() method, we cannot directly reference the blog list array value, so we need to call the then() method to parse one layer first, and then return the two synchronized values ??db and blogs. Note that this involves the nesting of Promise, but a Promise only nests one level of then().

這種方式,也是很蛋疼的一個方式,因為如果遇到then()方法中返回的不是同步的值,而是Promise的話,我們需要多做很多工作。而且,每次都透傳一個“多余”的db對象,在邏輯上也有點冗余。

但除此之外,對于Promise鏈的使用,如果遇到上面的問題,好像也沒其他更好的方法解決了。我們只能根據(jù)場景去選擇一種“最優(yōu)”的方案,如果要使用Promise鏈的話。

鑒于Promise上面蛋疼的問題,TJ大神將ES6中的生成器函數(shù),用co模塊包裝了一下,以更優(yōu)雅的方式來解決上面的問題。

co搭配生成器函數(shù)

如果使用co模塊搭配生成器函數(shù),那么上面的例子可以改寫如下:

const co = require('co');
co(function* (){
    let db = yield MongoClient.connect(url + db_name);
    let coll = db.collection('blogs');
    let blogs = yield coll.find().toArray();
    console.log(blogs.length);
    db.close();
}).catch(err => {
    console.log(err);
});

co是一個函數(shù),將接受一個生成器函數(shù)作為參數(shù),去執(zhí)行這個生成器函數(shù)。生成器函數(shù)中使用yield關鍵字來“同步”獲取每個異步操作的值。
上面代碼在代碼形式上,比上面使用Promise鏈要優(yōu)雅,我們消滅了回調函數(shù),代碼看起來都是同步的。除了使用co和yield有點怪之外。

使用co模塊,我們要將所有的操作包裝成一個生成器函數(shù),然后使用co()去調用這個生成器函數(shù)??瓷先ヒ策€可以接受,但是ES的進化是不滿足于此的,于是async/await被提到了ES7的提案。

async/await

我們先看一下使用async/await改寫上面的代碼:

(async function(){
    let db = await MongoClient.connect(url + db_name);
    let coll = db.collection('blogs');
    let blogs = await coll.find().toArray();
    console.log(blogs.length);
    db.close();
})().catch(err => {
    console.log(err);
});

我們對比代碼可以看出,async/await和co兩種方式代碼極為相似。co換成了async,yield換成了await。同時生成器函數(shù)變成了普通函數(shù)。這種方式在語義上更加清晰明了,async表明這個函數(shù)是異步的,同時await表示要“等待”異步操作返回值。

async函數(shù)返回一個Promise,上面的代碼其實是這樣:

let getBlogs = async function(){
    let db = await MongoClient.connect(url + db_name);
    let coll = db.collection('blogs');
    let blogs = await coll.find().toArray();
    db.close();
    return blogs;
};
getBlogs().then(result => {
    console.log(result.length);
}).catch(err => {
    console.log(err);
})

我們定義getBlogs為一個async函數(shù),最后返回得到的博客列表最終會被包裝成一個Promise返回,如上,我們直接調用getBlogs().then()方法可獲取async函數(shù)返回值。

好了,上面我們簡單對比了一下三種解決異步方案,下面我們來深入了解一下async/await。

深入async/await

async返回值

async用于定義一個異步函數(shù),該函數(shù)返回一個Promise。
如果async函數(shù)返回的是一個同步的值,這個值將被包裝成一個理解resolve的Promise,等同于return Promise.resolve(value)。
await用于一個異步操作之前,表示要“等待”這個異步操作的返回值。await也可以用于一個同步的值。

//返回一個Promise
let timer = async function timer(){
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve('500');
        },500);
    });
}
timer().then(result => {
  console.log(result);  //500
}).catch(err => {
    console.log(err.message);
});
//返回一個同步的值
let sayHi = async function sayHi(){
  let hi = await 'hello world';   
  return hi;  //等同于return Promise.resolve(hi);
}
sayHi().then(result => {
  console.log(result);
});

上面這個例子返回是一個同步的值,字符串’hello world’,sayHi()是一個async函數(shù),返回值被包裝成一個Promise,可以調用then()方法獲取返回值。對于一個同步的值,可以使用await,也可以不使用await。效果效果是一樣的。具體用不用,看情況。

比如上面使用mongodb查詢博客那個例子,let coll = db.collection('blogs');,這里我們就沒有用await,因為這是一個同步的值。當然,也可以使用await,這樣會顯得代碼統(tǒng)一。雖然效果是一樣的。

async函數(shù)的異常

let sayHi = async function sayHi(){
    throw new Error('出錯了');
}
sayHi().then(result => {
  console.log(result);
}).catch(err => {
    console.log(err.message);   //出錯了
});

我們直接在async函數(shù)中拋出一個異常,由于返回的是一個Promise,因此,這個異常可以調用返回Promise的catch()方法捕捉到。

和Promise鏈的對比:
我們的async函數(shù)中可以包含多個異步操作,其異常和Promise鏈有相同之處,如果有一個Promise被reject()那么后面的將不會再進行。

let count = ()=>{
    return new Promise((resolve,reject) => {
        setTimeout(()=>{
            reject('故意拋出錯誤');
        },500);
    });
}
let list = ()=>{
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve([1,2,3]);
        },500);
    });
}
let getList = async ()=>{
    let c = await count();
    let l = await list();
    return {count:c,list:l};
}
console.time('begin');
getList().then(result => {
    console.log(result);
}).catch(err => {
    console.timeEnd('begin');
    console.log(err);
});
//begin: 507.490ms
//故意拋出錯誤

如上面的代碼,定義兩個異步操作,count和list,使用setTimeout延時500毫秒,count故意直接拋出異常,從輸出結果來看,count()拋出異常后,直接由catch()捕捉到了,list()并沒有繼續(xù)執(zhí)行。

并行

使用async后,我們上面的例子都是串行的。比如上個list()和count()的例子,我們可以將這個例子用作分頁查詢數(shù)據(jù)的場景。先查詢出數(shù)據(jù)庫中總共有多少條記錄,然后再根據(jù)分頁條件查詢分頁數(shù)據(jù),最后返回分頁數(shù)據(jù)以及分頁信息。

我們上面的例子count()和list()有個“先后順序”,即我們先查的總數(shù),然后又查的列表。其實,這兩個操作并無先后關聯(lián)性,我們可以異步的同時進行查詢,然后等到所有結果都返回時再拼裝數(shù)據(jù)即可。

let count = ()=>{
    return new Promise((resolve,reject) => {
        setTimeout(()=>{
            resolve(100);
        },500);
    });
}
let list = ()=>{
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve([1,2,3]);
        },500);
    });
}
let getList = async ()=>{
    let result = await Promise.all([count(),list()]);
    return result;
}
console.time('begin');
getList().then(result => {
    console.timeEnd('begin');  //begin: 505.557ms
    console.log(result);       //[ 100, [ 1, 2, 3 ] ]
}).catch(err => {
    console.timeEnd('begin');
    console.log(err);
});

我們將count()和list()使用Promise.all()“同時”執(zhí)行,這里count()和list()可以看作是“并行”執(zhí)行的,所耗時間將是兩個異步操作中耗時最長的耗時。

The final result is an array composed of the results of the two operations. We just need to take out the values ????in the array in order.

[Recommended learning: javascript video tutorial]

The above is the detailed content of Is async for es6 or es7?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to reverse an array in ES6 How to reverse an array in ES6 Oct 26, 2022 pm 06:19 PM

In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

Is async for es6 or es7? Is async for es6 or es7? Jan 29, 2023 pm 05:36 PM

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

Why does the mini program need to convert es6 to es5? Why does the mini program need to convert es6 to es5? Nov 21, 2022 pm 06:15 PM

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

How to find different items in two arrays in es6 How to find different items in two arrays in es6 Nov 01, 2022 pm 06:07 PM

Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

How to implement array deduplication in es5 and es6 How to implement array deduplication in es5 and es6 Jan 16, 2023 pm 05:09 PM

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

What does es6 temporary Zenless Zone Zero mean? What does es6 temporary Zenless Zone Zero mean? Jan 03, 2023 pm 03:56 PM

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

How to determine how many items there are in an array in es6 How to determine how many items there are in an array in es6 Jan 18, 2023 pm 07:22 PM

In ES6, you can use the length attribute of the array object to determine how many items there are in the array, that is, to get the number of elements in the array; this attribute can return the number of elements in the array, just use the "array.length" statement. Returns a value representing the number of elements of the array object, that is, the length value.

Will es6 import promote variables? Will es6 import promote variables? Jan 18, 2023 pm 07:44 PM

ES6 import will cause variable promotion. Variable hoisting is the promotion of a variable declaration to the very beginning of its scope. js has to go through the compilation and execution phases. During the compilation phase, all variable declarations will be collected and variables declared in advance, and other statements will not change their order. Therefore, during the compilation phase, the first step is already is executed, and the second part is executed only when the statement is executed in the execution phase.

See all articles