日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

阮一峰老师的ES6入门:async 函数

發(fā)布時(shí)間:2023/11/27 生活经验 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 阮一峰老师的ES6入门:async 函数 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

async 函數(shù)

1. 含義

ES2017 標(biāo)準(zhǔn)引入了 async 函數(shù),使得異步操作變得更加方便。

async 函數(shù)是什么?一句話,它就是 Generator 函數(shù)的語法糖。

前文有一個(gè) Generator 函數(shù),依次讀取兩個(gè)文件。

const fs = require('fs'); const readFile = function (fileName) { return new Promise(function (resolve, reject) { fs.readFile(fileName, function(error, data) { if (error) return reject(error); resolve(data); }); }); }; const gen = function* () { const f1 = yield readFile('/etc/fstab'); const f2 = yield readFile('/etc/shells'); console.log(f1.toString()); console.log(f2.toString()); }; 

上面代碼的函數(shù)gen可以寫成async函數(shù),就是下面這樣。

const asyncReadFile = async function () { const f1 = await readFile('/etc/fstab'); const f2 = await readFile('/etc/shells'); console.log(f1.toString()); console.log(f2.toString()); }; 

一比較就會(huì)發(fā)現(xiàn),async函數(shù)就是將 Generator 函數(shù)的星號(*)替換成async,將yield替換成await,僅此而已。

async函數(shù)對 Generator 函數(shù)的改進(jìn),體現(xiàn)在以下四點(diǎn)。

(1)內(nèi)置執(zhí)行器。

Generator 函數(shù)的執(zhí)行必須靠執(zhí)行器,所以才有了co模塊,而async函數(shù)自帶執(zhí)行器。也就是說,async函數(shù)的執(zhí)行,與普通函數(shù)一模一樣,只要一行。

asyncReadFile(); 

上面的代碼調(diào)用了asyncReadFile函數(shù),然后它就會(huì)自動(dòng)執(zhí)行,輸出最后結(jié)果。這完全不像 Generator 函數(shù),需要調(diào)用next方法,或者用co模塊,才能真正執(zhí)行,得到最后結(jié)果。

(2)更好的語義。

asyncawait,比起星號和yield,語義更清楚了。async表示函數(shù)里有異步操作,await表示緊跟在后面的表達(dá)式需要等待結(jié)果。

(3)更廣的適用性。

co模塊約定,yield命令后面只能是 Thunk 函數(shù)或 Promise 對象,而async函數(shù)的await命令后面,可以是 Promise 對象和原始類型的值(數(shù)值、字符串和布爾值,但這時(shí)會(huì)自動(dòng)轉(zhuǎn)成立即 resolved 的 Promise 對象)。

(4)返回值是 Promise。

async函數(shù)的返回值是 Promise 對象,這比 Generator 函數(shù)的返回值是 Iterator 對象方便多了。你可以用then方法指定下一步的操作。

進(jìn)一步說,async函數(shù)完全可以看作多個(gè)異步操作,包裝成的一個(gè) Promise 對象,而await命令就是內(nèi)部then命令的語法糖。

2. 基本用法

async函數(shù)返回一個(gè) Promise 對象,可以使用then方法添加回調(diào)函數(shù)。當(dāng)函數(shù)執(zhí)行的時(shí)候,一旦遇到await就會(huì)先返回,等到異步操作完成,再接著執(zhí)行函數(shù)體內(nèi)后面的語句。

下面是一個(gè)例子。

async function getStockPriceByName(name) { const symbol = await getStockSymbol(name); const stockPrice = await getStockPrice(symbol); return stockPrice; } getStockPriceByName('goog').then(function (result) { console.log(result); }); 

上面代碼是一個(gè)獲取股票報(bào)價(jià)的函數(shù),函數(shù)前面的async關(guān)鍵字,表明該函數(shù)內(nèi)部有異步操作。調(diào)用該函數(shù)時(shí),會(huì)立即返回一個(gè)Promise對象。

下面是另一個(gè)例子,指定多少毫秒后輸出一個(gè)值。

function timeout(ms) { return new Promise((resolve) => { setTimeout(resolve, ms); }); } async function asyncPrint(value, ms) { await timeout(ms); console.log(value); } asyncPrint('hello world', 50); 

上面代碼指定 50 毫秒以后,輸出hello world

由于async函數(shù)返回的是 Promise 對象,可以作為await命令的參數(shù)。所以,上面的例子也可以寫成下面的形式。

async function timeout(ms) { await new Promise((resolve) => { setTimeout(resolve, ms); }); } async function asyncPrint(value, ms) { await timeout(ms); console.log(value); } asyncPrint('hello world', 50); 

async 函數(shù)有多種使用形式。

// 函數(shù)聲明
async function foo() {}  // 函數(shù)表達(dá)式 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(…);  // 箭頭函數(shù) const foo = async () => {}; 

3. 語法

async函數(shù)的語法規(guī)則總體上比較簡單,難點(diǎn)是錯(cuò)誤處理機(jī)制。

返回 Promise 對象

async函數(shù)返回一個(gè) Promise 對象。

async函數(shù)內(nèi)部return語句返回的值,會(huì)成為then方法回調(diào)函數(shù)的參數(shù)。

async function f() { return 'hello world'; } f().then(v => console.log(v)) // "hello world" 

上面代碼中,函數(shù)f內(nèi)部return命令返回的值,會(huì)被then方法回調(diào)函數(shù)接收到。

async函數(shù)內(nèi)部拋出錯(cuò)誤,會(huì)導(dǎo)致返回的 Promise 對象變?yōu)?code>reject狀態(tài)。拋出的錯(cuò)誤對象會(huì)被catch方法回調(diào)函數(shù)接收到。

async function f() { throw new Error('出錯(cuò)了'); } f().then( v => console.log(v), e => console.log(e) ) // Error: 出錯(cuò)了 

Promise 對象的狀態(tài)變化

async函數(shù)返回的 Promise 對象,必須等到內(nèi)部所有await命令后面的 Promise 對象執(zhí)行完,才會(huì)發(fā)生狀態(tài)改變,除非遇到return語句或者拋出錯(cuò)誤。也就是說,只有async函數(shù)內(nèi)部的異步操作執(zhí)行完,才會(huì)執(zhí)行then方法指定的回調(diào)函數(shù)。

下面是一個(gè)例子。

async function getTitle(url) { let response = await fetch(url); let html = await response.text(); return html.match(/<title>([\s\S]+)<\/title>/i)[1]; } getTitle('https://tc39.github.io/ecma262/').then(console.log) // "ECMAScript 2017 Language Specification" 

上面代碼中,函數(shù)getTitle內(nèi)部有三個(gè)操作:抓取網(wǎng)頁、取出文本、匹配頁面標(biāo)題。只有這三個(gè)操作全部完成,才會(huì)執(zhí)行then方法里面的console.log

await 命令

正常情況下,await命令后面是一個(gè) Promise 對象,返回該對象的結(jié)果。如果不是 Promise 對象,就直接返回對應(yīng)的值。

async function f() {  // 等同于  // return 123; return await 123; } f().then(v => console.log(v)) // 123 

上面代碼中,await命令的參數(shù)是數(shù)值123,這時(shí)等同于return 123。

另一種情況是,await命令后面是一個(gè)thenable對象(即定義then方法的對象),那么await會(huì)將其等同于 Promise 對象。

class Sleep {constructor(timeout) { this.timeout = timeout; } then(resolve, reject) { const startTime = Date.now(); setTimeout( () => resolve(Date.now() - startTime), this.timeout ); } } (async () => { const actualTime = await new Sleep(1000); console.log(actualTime); })(); 

上面代碼中,await命令后面是一個(gè)Sleep對象的實(shí)例。這個(gè)實(shí)例不是 Promise 對象,但是因?yàn)槎x了then方法,await會(huì)將其視為Promise處理。

await命令后面的 Promise 對象如果變?yōu)?code>reject狀態(tài),則reject的參數(shù)會(huì)被catch方法的回調(diào)函數(shù)接收到。

async function f() { await Promise.reject('出錯(cuò)了'); } f() .then(v => console.log(v)) .catch(e => console.log(e)) // 出錯(cuò)了 

注意,上面代碼中,await語句前面沒有return,但是reject方法的參數(shù)依然傳入了catch方法的回調(diào)函數(shù)。這里如果在await前面加上return,效果是一樣的。

任何一個(gè)await語句后面的 Promise 對象變?yōu)?code>reject狀態(tài),那么整個(gè)async函數(shù)都會(huì)中斷執(zhí)行。

async function f() { await Promise.reject('出錯(cuò)了'); await Promise.resolve('hello world'); // 不會(huì)執(zhí)行 } 

上面代碼中,第二個(gè)await語句是不會(huì)執(zhí)行的,因?yàn)榈谝粋€(gè)await語句狀態(tài)變成了reject。

有時(shí),我們希望即使前一個(gè)異步操作失敗,也不要中斷后面的異步操作。這時(shí)可以將第一個(gè)await放在try...catch結(jié)構(gòu)里面,這樣不管這個(gè)異步操作是否成功,第二個(gè)await都會(huì)執(zhí)行。

async function f() { try { await Promise.reject('出錯(cuò)了'); } catch(e) { } return await Promise.resolve('hello world'); } f() .then(v => console.log(v)) // hello world 

另一種方法是await后面的 Promise 對象再跟一個(gè)catch方法,處理前面可能出現(xiàn)的錯(cuò)誤。

async function f() { await Promise.reject('出錯(cuò)了') .catch(e => console.log(e)); return await Promise.resolve('hello world'); } f() .then(v => console.log(v)) // 出錯(cuò)了 // hello world 

錯(cuò)誤處理

如果await后面的異步操作出錯(cuò),那么等同于async函數(shù)返回的 Promise 對象被reject。

async function f() { await new Promise(function (resolve, reject) { throw new Error('出錯(cuò)了'); }); } f() .then(v => console.log(v)) .catch(e => console.log(e)) // Error:出錯(cuò)了 

上面代碼中,async函數(shù)f執(zhí)行后,await后面的 Promise 對象會(huì)拋出一個(gè)錯(cuò)誤對象,導(dǎo)致catch方法的回調(diào)函數(shù)被調(diào)用,它的參數(shù)就是拋出的錯(cuò)誤對象。具體的執(zhí)行機(jī)制,可以參考后文的“async 函數(shù)的實(shí)現(xiàn)原理”。

防止出錯(cuò)的方法,也是將其放在try...catch代碼塊之中。

async function f() { try { await new Promise(function (resolve, reject) { throw new Error('出錯(cuò)了'); }); } catch(e) { } return await('hello world'); } 

如果有多個(gè)await命令,可以統(tǒng)一放在try...catch結(jié)構(gòu)中。

async function main() { try { const val1 = await firstStep(); const val2 = await secondStep(val1); const val3 = await thirdStep(val1, val2); console.log('Final: ', val3); } catch (err) { console.error(err); } } 

下面的例子使用try...catch結(jié)構(gòu),實(shí)現(xiàn)多次重復(fù)嘗試。

const superagent = require('superagent'); const NUM_RETRIES = 3; async function test() { let i; for (i = 0; i < NUM_RETRIES; ++i) { try { await superagent.get('http://google.com/this-throws-an-error'); break; } catch(err) {} } console.log(i); // 3 } test(); 

上面代碼中,如果await操作成功,就會(huì)使用break語句退出循環(huán);如果失敗,會(huì)被catch語句捕捉,然后進(jìn)入下一輪循環(huán)。

使用注意點(diǎn)

第一點(diǎn),前面已經(jīng)說過,await命令后面的Promise對象,運(yùn)行結(jié)果可能是rejected,所以最好把await命令放在try...catch代碼塊中。

async function myFunction() { try { await somethingThatReturnsAPromise(); } catch (err) { console.log(err); } }  // 另一種寫法 async function myFunction() { await somethingThatReturnsAPromise() .catch(function (err) { console.log(err); }); } 

第二點(diǎn),多個(gè)await命令后面的異步操作,如果不存在繼發(fā)關(guān)系,最好讓它們同時(shí)觸發(fā)。

let foo = await getFoo(); let bar = await getBar(); 

上面代碼中,getFoogetBar是兩個(gè)獨(dú)立的異步操作(即互不依賴),被寫成繼發(fā)關(guān)系。這樣比較耗時(shí),因?yàn)橹挥?code>getFoo完成以后,才會(huì)執(zhí)行getBar完全可以讓它們同時(shí)觸發(fā)。

// 寫法一
let [foo, bar] = await Promise.all([getFoo(), getBar()]);  // 寫法二 let fooPromise = getFoo(); let barPromise = getBar(); let foo = await fooPromise; let bar = await barPromise; 

上面兩種寫法,getFoogetBar都是同時(shí)觸發(fā),這樣就會(huì)縮短程序的執(zhí)行時(shí)間。

第三點(diǎn),await命令只能用在async函數(shù)之中,如果用在普通函數(shù),就會(huì)報(bào)錯(cuò)。

async function dbFuc(db) { let docs = [{}, {}, {}];  // 報(bào)錯(cuò) docs.forEach(function (doc) { await db.post(doc); }); } 

上面代碼會(huì)報(bào)錯(cuò),因?yàn)?code>await用在普通函數(shù)之中了。但是,如果將forEach方法的參數(shù)改成async函數(shù),也有問題。

function dbFuc(db) { //這里不需要 async let docs = [{}, {}, {}];  // 可能得到錯(cuò)誤結(jié)果 docs.forEach(async function (doc) { await db.post(doc); }); } 

上面代碼可能不會(huì)正常工作,原因是這時(shí)三個(gè)db.post操作將是并發(fā)執(zhí)行,也就是同時(shí)執(zhí)行,而不是繼發(fā)執(zhí)行。正確的寫法是采用for循環(huán)。

async function dbFuc(db) { let docs = [{}, {}, {}]; for (let doc of docs) { await db.post(doc); } } 

如果確實(shí)希望多個(gè)請求并發(fā)執(zhí)行,可以使用Promise.all方法。當(dāng)三個(gè)請求都會(huì)resolved時(shí),下面兩種寫法效果相同。

async function dbFuc(db) { let docs = [{}, {}, {}]; let promises = docs.map((doc) => db.post(doc)); let results = await Promise.all(promises); console.log(results); }  // 或者使用下面的寫法 async function dbFuc(db) { let docs = [{}, {}, {}]; let promises = docs.map((doc) => db.post(doc)); let results = []; for (let promise of promises) { results.push(await promise); } console.log(results); } 

第四點(diǎn),async 函數(shù)可以保留運(yùn)行堆棧。

const a = () => { b().then(() => c()); }; 

上面代碼中,函數(shù)a內(nèi)部運(yùn)行了一個(gè)異步任務(wù)b()。當(dāng)b()運(yùn)行的時(shí)候,函數(shù)a()不會(huì)中斷,而是繼續(xù)執(zhí)行。等到b()運(yùn)行結(jié)束,可能a()早就運(yùn)行結(jié)束了,b()所在的上下文環(huán)境已經(jīng)消失了。如果b()c()報(bào)錯(cuò),錯(cuò)誤堆棧將不包括a()

現(xiàn)在將這個(gè)例子改成async函數(shù)。

const a = async () => { await b(); c(); }; 

上面代碼中,b()運(yùn)行的時(shí)候,a()是暫停執(zhí)行,上下文環(huán)境都保存著。一旦b()c()報(bào)錯(cuò),錯(cuò)誤堆棧將包括a()。

4. async 函數(shù)的實(shí)現(xiàn)原理

async 函數(shù)的實(shí)現(xiàn)原理,就是將 Generator 函數(shù)和自動(dòng)執(zhí)行器,包裝在一個(gè)函數(shù)里。

async function fn(args) {  // ... }  // 等同于 function fn(args) { return spawn(function* () {  // ... }); } 

所有的async函數(shù)都可以寫成上面的第二種形式,其中的spawn函數(shù)就是自動(dòng)執(zhí)行器。

下面給出spawn函數(shù)的實(shí)現(xiàn),基本就是前文自動(dòng)執(zhí)行器的翻版。

function spawn(genF) { return new Promise(function(resolve, reject) { const gen = genF(); function step(nextF) { let next; try { next = nextF(); } catch(e) { return reject(e); } if(next.done) { return resolve(next.value); } Promise.resolve(next.value).then(function(v) { step(function() { return gen.next(v); }); }, function(e) { step(function() { return gen.throw(e); }); }); } step(function() { return gen.next(undefined); }); }); } 

5. 與其他異步處理方法的比較

我們通過一個(gè)例子,來看 async 函數(shù)與 Promise、Generator 函數(shù)的比較。

假定某個(gè) DOM 元素上面,部署了一系列的動(dòng)畫,前一個(gè)動(dòng)畫結(jié)束,才能開始后一個(gè)。如果當(dāng)中有一個(gè)動(dòng)畫出錯(cuò),就不再往下執(zhí)行,返回上一個(gè)成功執(zhí)行的動(dòng)畫的返回值。

首先是 Promise 的寫法。

function chainAnimationsPromise(elem, animations) {  // 變量ret用來保存上一個(gè)動(dòng)畫的返回值 let ret = null;  // 新建一個(gè)空的Promise let p = Promise.resolve();  // 使用then方法,添加所有動(dòng)畫 for(let anim of animations) { p = p.then(function(val) { ret = val; return anim(elem); }); }  // 返回一個(gè)部署了錯(cuò)誤捕捉機(jī)制的Promise return p.catch(function(e) { /* 忽略錯(cuò)誤,繼續(xù)執(zhí)行 */ }).then(function() { return ret; }); } 

雖然 Promise 的寫法比回調(diào)函數(shù)的寫法大大改進(jìn),但是一眼看上去,代碼完全都是 Promise 的 API(then、catch等等),操作本身的語義反而不容易看出來。

接著是 Generator 函數(shù)的寫法。

function chainAnimationsGenerator(elem, animations) { return spawn(function*() { let ret = null; try { for(let anim of animations) { ret = yield anim(elem); } } catch(e) { /* 忽略錯(cuò)誤,繼續(xù)執(zhí)行 */ } return ret; }); } 

上面代碼使用 Generator 函數(shù)遍歷了每個(gè)動(dòng)畫,語義比 Promise 寫法更清晰,用戶定義的操作全部都出現(xiàn)在spawn函數(shù)的內(nèi)部。這個(gè)寫法的問題在于,必須有一個(gè)任務(wù)運(yùn)行器,自動(dòng)執(zhí)行 Generator 函數(shù),上面代碼的spawn函數(shù)就是自動(dòng)執(zhí)行器,它返回一個(gè) Promise 對象,而且必須保證yield語句后面的表達(dá)式,必須返回一個(gè) Promise。

最后是 async 函數(shù)的寫法。

async function chainAnimationsAsync(elem, animations) { let ret = null; try { for(let anim of animations) { ret = await anim(elem); } } catch(e) { /* 忽略錯(cuò)誤,繼續(xù)執(zhí)行 */ } return ret; } 

可以看到 Async 函數(shù)的實(shí)現(xiàn)最簡潔,最符合語義,幾乎沒有語義不相關(guān)的代碼。它將 Generator 寫法中的自動(dòng)執(zhí)行器,改在語言層面提供,不暴露給用戶,因此代碼量最少。如果使用 Generator 寫法,自動(dòng)執(zhí)行器需要用戶自己提供。

6. 實(shí)例:按順序完成異步操作

實(shí)際開發(fā)中,經(jīng)常遇到一組異步操作,需要按照順序完成。比如,依次遠(yuǎn)程讀取一組 URL,然后按照讀取的順序輸出結(jié)果。

Promise 的寫法如下。

function logInOrder(urls) {  // 遠(yuǎn)程讀取所有URL const textPromises = urls.map(url => { return fetch(url).then(response => response.text()); });  // 按次序輸出 textPromises.reduce((chain, textPromise) => { return chain.then(() => textPromise) .then(text => console.log(text)); }, Promise.resolve()); } 

上面代碼使用fetch方法,同時(shí)遠(yuǎn)程讀取一組 URL。每個(gè)fetch操作都返回一個(gè) Promise 對象,放入textPromises數(shù)組。然后,reduce方法依次處理每個(gè) Promise 對象,然后使用then,將所有 Promise 對象連起來,因此就可以依次輸出結(jié)果。

這種寫法不太直觀,可讀性比較差。下面是 async 函數(shù)實(shí)現(xiàn)。

async function logInOrder(urls) { for (const url of urls) { const response = await fetch(url); console.log(await response.text()); } } 

上面代碼確實(shí)大大簡化,問題是所有遠(yuǎn)程操作都是繼發(fā)。只有前一個(gè) URL 返回結(jié)果,才會(huì)去讀取下一個(gè) URL,這樣做效率很差,非常浪費(fèi)時(shí)間。我們需要的是并發(fā)發(fā)出遠(yuǎn)程請求。

async function logInOrder(urls) {  // 并發(fā)讀取遠(yuǎn)程URL const textPromises = urls.map(async url => { const response = await fetch(url); return response.text(); });  // 按次序輸出 for (const textPromise of textPromises) { console.log(await textPromise); } } 

上面代碼中,雖然map方法的參數(shù)是async函數(shù),但它是并發(fā)執(zhí)行的,因?yàn)橹挥?code>async函數(shù)內(nèi)部是繼發(fā)執(zhí)行,外部不受影響。后面的for..of循環(huán)內(nèi)部使用了await,因此實(shí)現(xiàn)了按順序輸出。

7. 頂層 await

根據(jù)語法規(guī)格,await命令只能出現(xiàn)在 async 函數(shù)內(nèi)部,否則都會(huì)報(bào)錯(cuò)。

// 報(bào)錯(cuò)
const data = await fetch('https://api.example.com'); 

上面代碼中,await命令獨(dú)立使用,沒有放在 async 函數(shù)里面,就會(huì)報(bào)錯(cuò)。

目前,有一個(gè)語法提案,允許在模塊的頂層獨(dú)立使用await命令。這個(gè)提案的目的,是借用await解決模塊異步加載的問題。

// awaiting.js
let output;
async function main() { const dynamic = await import(someMission); const data = await fetch(url); output = someProcess(dynamic.default, data); } main(); export { output }; 

上面代碼中,模塊awaiting.js的輸出值output,取決于異步操作。我們把異步操作包裝在一個(gè) async 函數(shù)里面,然后調(diào)用這個(gè)函數(shù),只有等里面的異步操作都執(zhí)行,變量output才會(huì)有值,否則就返回undefined。

上面的代碼也可以寫成立即執(zhí)行函數(shù)的形式。

// awaiting.js
let output;
(async function main() { const dynamic = await import(someMission); const data = await fetch(url); output = someProcess(dynamic.default, data); })(); export { output }; 

下面是加載這個(gè)模塊的寫法。

// usage.js
import { output } from "./awaiting.js"; function outputPlusValue(value) { return output + value } console.log(outputPlusValue(100)); setTimeout(() => console.log(outputPlusValue(100), 1000); 

上面代碼中,outputPlusValue()的執(zhí)行結(jié)果,完全取決于執(zhí)行的時(shí)間。如果awaiting.js里面的異步操作沒執(zhí)行完,加載進(jìn)來的output的值就是undefined。

目前的解決方法,就是讓原始模塊輸出一個(gè) Promise 對象,從這個(gè) Promise 對象判斷異步操作有沒有結(jié)束。

// awaiting.js
let output;
export default (async function main() { const dynamic = await import(someMission); const data = await fetch(url); output = someProcess(dynamic.default, data); })(); export { output }; 

上面代碼中,awaiting.js除了輸出output,還默認(rèn)輸出一個(gè) Promise 對象(async 函數(shù)立即執(zhí)行后,返回一個(gè) Promise 對象),從這個(gè)對象判斷異步操作是否結(jié)束。

下面是加載這個(gè)模塊的新的寫法。

// usage.js
import promise, { output } from "./awaiting.js"; function outputPlusValue(value) { return output + value } promise.then(() => { console.log(outputPlusValue(100)); setTimeout(() => console.log(outputPlusValue(100), 1000); }); 

上面代碼中,將awaiting.js對象的輸出,放在promise.then()里面,這樣就能保證異步操作完成以后,才去讀取output

這種寫法比較麻煩,等于要求模塊的使用者遵守一個(gè)額外的使用協(xié)議,按照特殊的方法使用這個(gè)模塊。一旦你忘了要用 Promise 加載,只使用正常的加載方法,依賴這個(gè)模塊的代碼就可能出錯(cuò)。而且,如果上面的usage.js又有對外的輸出,等于這個(gè)依賴鏈的所有模塊都要使用 Promise 加載。

頂層的await命令,就是為了解決這個(gè)問題。它保證只有異步操作完成,模塊才會(huì)輸出值。

// awaiting.js
const dynamic = import(someMission); const data = fetch(url); export const output = someProcess((await dynamic).default, await data); 

上面代碼中,兩個(gè)異步操作在輸出的時(shí)候,都加上了await命令。只有等到異步操作完成,這個(gè)模塊才會(huì)輸出值。

加載這個(gè)模塊的寫法如下。

// usage.js
import { output } from "./awaiting.js"; function outputPlusValue(value) { return output + value } console.log(outputPlusValue(100)); setTimeout(() => console.log(outputPlusValue(100), 1000); 

上面代碼的寫法,與普通的模塊加載完全一樣。也就是說,模塊的使用者完全不用關(guān)心,依賴模塊的內(nèi)部有沒有異步操作,正常加載即可。

這時(shí),模塊的加載會(huì)等待依賴模塊(上例是awaiting.js)的異步操作完成,才執(zhí)行后面的代碼,有點(diǎn)像暫停在那里。所以,它總是會(huì)得到正確的output,不會(huì)因?yàn)榧虞d時(shí)機(jī)的不同,而得到不一樣的值。

下面是頂層await的一些使用場景。

// import() 方法加載
const strings = await import(`/i18n/${navigator.language}`);  // 數(shù)據(jù)庫操作 const connection = await dbConnector();  // 依賴回滾 let jQuery; try { jQuery = await import('https://cdn-a.com/jQuery'); } catch { jQuery = await import('https://cdn-b.com/jQuery'); } 

注意,如果加載多個(gè)包含頂層await命令的模塊,加載命令是同步執(zhí)行的。

// x.js
console.log("X1"); await new Promise(r => setTimeout(r, 1000)); console.log("X2");  // y.js console.log("Y");  // z.js import "./x.js"; import "./y.js"; console.log("Z"); 

上面代碼有三個(gè)模塊,最后的z.js加載x.jsy.js,打印結(jié)果是X1、Y、X2、Z。這說明,z.js并沒有等待x.js加載完成,再去加載y.js

頂層的await命令有點(diǎn)像,交出代碼的執(zhí)行權(quán)給其他的模塊加載,等異步操作完成后,再拿回執(zhí)行權(quán),繼續(xù)向下執(zhí)行。

轉(zhuǎn)載于:https://www.cnblogs.com/moumoon/p/10999771.html

總結(jié)

以上是生活随笔為你收集整理的阮一峰老师的ES6入门:async 函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。