async 函數(shù)(轉(zhuǎn)載)

async 函數(shù)

含義

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

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

前文有一個(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());
};

寫成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ù)的星號(hào)(*)替換成async,將yield替換成await,僅此而已。

async函數(shù)對(duì) 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)更好的語(yǔ)義。

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

(3)更廣的適用性。

co模塊約定,yield命令后面只能是 Thunk 函數(shù)或 Promise 對(duì)象,而async函數(shù)的await命令后面,可以是Promise 對(duì)象和原始類型的值(數(shù)值、字符串和布爾值,但這時(shí)等同于同步操作)。

(4)返回值是 Promise。

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

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

基本用法

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

下面是一個(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對(duì)象。

下面是另一個(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 對(duì)象,可以作為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 () {};

// 對(duì)象的方法
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 () => {};

語(yǔ)法

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

返回 Promise 對(duì)象

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

async函數(shù)內(nèi)部return語(yǔ)句返回的值,會(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 對(duì)象變?yōu)?code>reject狀態(tài)。拋出的錯(cuò)誤對(duì)象會(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 對(duì)象的狀態(tài)變化

async函數(shù)返回的 Promise 對(duì)象,必須等到內(nèi)部所有await命令后面的 Promise 對(duì)象執(zhí)行完,才會(huì)發(fā)生狀態(tài)改變,除非遇到return語(yǔ)句或者拋出錯(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)頁(yè)、取出文本、匹配頁(yè)面標(biāo)題。只有這三個(gè)操作全部完成,才會(huì)執(zhí)行then方法里面的console.log

await 命令

正常情況下,await命令后面是一個(gè) Promise 對(duì)象。如果不是,會(huì)被轉(zhuǎn)成一個(gè)立即resolve的 Promise 對(duì)象。

async function f() {
  return await 123;
}

f().then(v => console.log(v))
// 123

上面代碼中,await命令的參數(shù)是數(shù)值123,它被轉(zhuǎn)成 Promise 對(duì)象,并立即resolve。

await命令后面的 Promise 對(duì)象如果變?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語(yǔ)句前面沒有return,但是reject方法的參數(shù)依然傳入了catch方法的回調(diào)函數(shù)。這里如果在await前面加上return,效果是一樣的。

只要一個(gè)await語(yǔ)句后面的 Promise 變?yōu)?code>reject,那么整個(gè)async函數(shù)都會(huì)中斷執(zhí)行。

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

上面代碼中,第二個(gè)await語(yǔ)句是不會(huì)執(zhí)行的,因?yàn)榈谝粋€(gè)await語(yǔ)句狀態(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 對(duì)象再跟一個(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 對(duì)象被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 對(duì)象會(huì)拋出一個(gè)錯(cuò)誤對(duì)象,導(dǎo)致catch方法的回調(diào)函數(shù)被調(diào)用,它的參數(shù)就是拋出的錯(cuò)誤對(duì)象。具體的執(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語(yǔ)句退出循環(huán);如果失敗,會(huì)被catch語(yǔ)句捕捉,然后進(jìn)入下一輪循環(huán)。

使用注意點(diǎn)

第一點(diǎn),前面已經(jīng)說過,await命令后面的Promise對(duì)象,運(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è)請(qǐng)求并發(fā)執(zhí)行,可以使用Promise.all方法。當(dāng)三個(gè)請(qǐng)求都會(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);
}

目前,@std/esm模塊加載器支持頂層await,即await命令可以不放在 async 函數(shù)里面,直接使用。

// async 函數(shù)的寫法
const start = async () => {
  const res = await fetch('google.com');
  return res.text();
};

start().then(console.log);

// 頂層 await 的寫法
const res = await fetch('google.com');
console.log(await res.text());

上面代碼中,第二種寫法的腳本必須使用@std/esm加載器,才會(huì)生效。

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); });
  });
}

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

我們通過一個(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(thencatch等等),操作本身的語(yǔ)義反而不容易看出來。

接著是 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)畫,語(yǔ)義比 Promise 寫法更清晰,用戶定義的操作全部都出現(xiàn)在spawn函數(shù)的內(nèi)部。這個(gè)寫法的問題在于,必須有一個(gè)任務(wù)運(yùn)行器,自動(dòng)執(zhí)行 Generator 函數(shù),上面代碼的spawn函數(shù)就是自動(dòng)執(zhí)行器,它返回一個(gè) Promise 對(duì)象,而且必須保證yield語(yǔ)句后面的表達(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)最簡(jiǎn)潔,最符合語(yǔ)義,幾乎沒有語(yǔ)義不相關(guān)的代碼。它將Generator寫法中的自動(dòng)執(zhí)行器,改在語(yǔ)言層面提供,不暴露給用戶,因此代碼量最少。如果使用Generator寫法,自動(dòng)執(zhí)行器需要用戶自己提供。

實(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 對(duì)象,放入textPromises數(shù)組。然后,reduce方法依次處理每個(gè) Promise 對(duì)象,然后使用then,將所有 Promise 對(duì)象連起來,因此就可以依次輸出結(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í)大大簡(jiǎn)化,問題是所有遠(yuǎn)程操作都是繼發(fā)。只有前一個(gè)URL返回結(jié)果,才會(huì)去讀取下一個(gè)URL,這樣做效率很差,非常浪費(fèi)時(shí)間。我們需要的是并發(fā)發(fā)出遠(yuǎn)程請(qǐng)求。

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)了按順序輸出。

異步遍歷器

《遍歷器》一章說過,Iterator 接口是一種數(shù)據(jù)遍歷的協(xié)議,只要調(diào)用遍歷器對(duì)象的next方法,就會(huì)得到一個(gè)對(duì)象,表示當(dāng)前遍歷指針?biāo)诘哪莻€(gè)位置的信息。next方法返回的對(duì)象的結(jié)構(gòu)是{value, done},其中value表示當(dāng)前的數(shù)據(jù)的值,done是一個(gè)布爾值,表示遍歷是否結(jié)束。

這里隱含著一個(gè)規(guī)定,next方法必須是同步的,只要調(diào)用就必須立刻返回值。也就是說,一旦執(zhí)行next方法,就必須同步地得到valuedone這兩個(gè)屬性。如果遍歷指針正好指向同步操作,當(dāng)然沒有問題,但對(duì)于異步操作,就不太合適了。目前的解決方法是,Generator 函數(shù)里面的異步操作,返回一個(gè) Thunk 函數(shù)或者 Promise 對(duì)象,即value屬性是一個(gè) Thunk 函數(shù)或者 Promise 對(duì)象,等待以后返回真正的值,而done屬性則還是同步產(chǎn)生的。

目前,有一個(gè)提案,為異步操作提供原生的遍歷器接口,即valuedone這兩個(gè)屬性都是異步產(chǎn)生,這稱為”異步遍歷器“(Async Iterator)。

異步遍歷的接口

異步遍歷器的最大的語(yǔ)法特點(diǎn),就是調(diào)用遍歷器的next方法,返回的是一個(gè) Promise 對(duì)象。

asyncIterator
  .next()
  .then(
    ({ value, done }) => /* ... */
  );

上面代碼中,asyncIterator是一個(gè)異步遍歷器,調(diào)用next方法以后,返回一個(gè) Promise 對(duì)象。因此,可以使用then方法指定,這個(gè) Promise 對(duì)象的狀態(tài)變?yōu)?code>resolve以后的回調(diào)函數(shù)。回調(diào)函數(shù)的參數(shù),則是一個(gè)具有valuedone兩個(gè)屬性的對(duì)象,這個(gè)跟同步遍歷器是一樣的。

我們知道,一個(gè)對(duì)象的同步遍歷器的接口,部署在Symbol.iterator屬性上面。同樣地,對(duì)象的異步遍歷器接口,部署在Symbol.asyncIterator屬性上面。不管是什么樣的對(duì)象,只要它的Symbol.asyncIterator屬性有值,就表示應(yīng)該對(duì)它進(jìn)行異步遍歷。

下面是一個(gè)異步遍歷器的例子。

const asyncIterable = createAsyncIterable(['a', 'b']);
const asyncIterator = asyncIterable[Symbol.asyncIterator]();

asyncIterator
.next()
.then(iterResult1 => {
  console.log(iterResult1); // { value: 'a', done: false }
  return asyncIterator.next();
})
.then(iterResult2 => {
  console.log(iterResult2); // { value: 'b', done: false }
  return asyncIterator.next();
})
.then(iterResult3 => {
  console.log(iterResult3); // { value: undefined, done: true }
});

上面代碼中,異步遍歷器其實(shí)返回了兩次值。第一次調(diào)用的時(shí)候,返回一個(gè) Promise 對(duì)象;等到 Promise 對(duì)象resolve了,再返回一個(gè)表示當(dāng)前數(shù)據(jù)成員信息的對(duì)象。這就是說,異步遍歷器與同步遍歷器最終行為是一致的,只是會(huì)先返回 Promise 對(duì)象,作為中介。

由于異步遍歷器的next方法,返回的是一個(gè) Promise 對(duì)象。因此,可以把它放在await命令后面。

async function f() {
  const asyncIterable = createAsyncIterable(['a', 'b']);
  const asyncIterator = asyncIterable[Symbol.asyncIterator]();
  console.log(await asyncIterator.next());
  // { value: 'a', done: false }
  console.log(await asyncIterator.next());
  // { value: 'b', done: false }
  console.log(await asyncIterator.next());
  // { value: undefined, done: true }
}

上面代碼中,next方法用await處理以后,就不必使用then方法了。整個(gè)流程已經(jīng)很接近同步處理了。

注意,異步遍歷器的next方法是可以連續(xù)調(diào)用的,不必等到上一步產(chǎn)生的Promise對(duì)象resolve以后再調(diào)用。這種情況下,next方法會(huì)累積起來,自動(dòng)按照每一步的順序運(yùn)行下去。下面是一個(gè)例子,把所有的next方法放在Promise.all方法里面。

const asyncGenObj = createAsyncIterable(['a', 'b']);
const [{value: v1}, {value: v2}] = await Promise.all([
  asyncGenObj.next(), asyncGenObj.next()
]);

console.log(v1, v2); // a b

另一種用法是一次性調(diào)用所有的next方法,然后await最后一步操作。

const writer = openFile('someFile.txt');
writer.next('hello');
writer.next('world');
await writer.return();

for await...of

前面介紹過,for...of循環(huán)用于遍歷同步的 Iterator 接口。新引入的for await...of循環(huán),則是用于遍歷異步的 Iterator 接口。

async function f() {
  for await (const x of createAsyncIterable(['a', 'b'])) {
    console.log(x);
  }
}
// a
// b

上面代碼中,createAsyncIterable()返回一個(gè)異步遍歷器,for...of循環(huán)自動(dòng)調(diào)用這個(gè)遍歷器的next方法,會(huì)得到一個(gè)Promise對(duì)象。await用來處理這個(gè)Promise對(duì)象,一旦resolve,就把得到的值(x)傳入for...of的循環(huán)體。

for await...of循環(huán)的一個(gè)用途,是部署了 asyncIterable 操作的異步接口,可以直接放入這個(gè)循環(huán)。

let body = '';

async function f() {
  for await(const data of req) body += data;
  const parsed = JSON.parse(body);
  console.log('got', parsed);
}

上面代碼中,req是一個(gè) asyncIterable 對(duì)象,用來異步讀取數(shù)據(jù)??梢钥吹?,使用for await...of循環(huán)以后,代碼會(huì)非常簡(jiǎn)潔。

如果next方法返回的 Promise 對(duì)象被rejectfor await...of就會(huì)報(bào)錯(cuò),要用try...catch捕捉。

async function () {
  try {
    for await (const x of createRejectingIterable()) {
      console.log(x);
    }
  } catch (e) {
    console.error(e);
  }
}

注意,for await...of循環(huán)也可以用于同步遍歷器。

(async function () {
  for await (const x of ['a', 'b']) {
    console.log(x);
  }
})();
// a
// b

異步 Generator 函數(shù)

就像 Generator 函數(shù)返回一個(gè)同步遍歷器對(duì)象一樣,異步 Generator 函數(shù)的作用,是返回一個(gè)異步遍歷器對(duì)象。

在語(yǔ)法上,異步 Generator 函數(shù)就是async函數(shù)與 Generator 函數(shù)的結(jié)合。

async function* gen() {
  yield 'hello';
}
const genObj = gen();
genObj.next().then(x => console.log(x));
// { value: 'hello', done: false }

上面代碼中,gen是一個(gè)異步 Generator 函數(shù),執(zhí)行后返回一個(gè)異步 Iterator 對(duì)象。對(duì)該對(duì)象調(diào)用next方法,返回一個(gè) Promise 對(duì)象。

異步遍歷器的設(shè)計(jì)目的之一,就是 Generator 函數(shù)處理同步操作和異步操作時(shí),能夠使用同一套接口。

// 同步 Generator 函數(shù)
function* map(iterable, func) {
  const iter = iterable[Symbol.iterator]();
  while (true) {
    const {value, done} = iter.next();
    if (done) break;
    yield func(value);
  }
}

// 異步 Generator 函數(shù)
async function* map(iterable, func) {
  const iter = iterable[Symbol.asyncIterator]();
  while (true) {
    const {value, done} = await iter.next();
    if (done) break;
    yield func(value);
  }
}

上面代碼中,可以看到有了異步遍歷器以后,同步 Generator 函數(shù)和異步 Generator 函數(shù)的寫法基本上是一致的。

下面是另一個(gè)異步 Generator 函數(shù)的例子。

async function* readLines(path) {
  let file = await fileOpen(path);

  try {
    while (!file.EOF) {
      yield await file.readLine();
    }
  } finally {
    await file.close();
  }
}

上面代碼中,異步操作前面使用await關(guān)鍵字標(biāo)明,即await后面的操作,應(yīng)該返回 Promise 對(duì)象。凡是使用yield關(guān)鍵字的地方,就是next方法的停下來的地方,它后面的表達(dá)式的值(即await file.readLine()的值),會(huì)作為next()返回對(duì)象的value屬性,這一點(diǎn)是與同步 Generator 函數(shù)一致的。

異步 Generator 函數(shù)內(nèi)部,能夠同時(shí)使用awaityield命令??梢赃@樣理解,await命令用于將外部操作產(chǎn)生的值輸入函數(shù)內(nèi)部,yield命令用于將函數(shù)內(nèi)部的值輸出。

上面代碼定義的異步 Generator 函數(shù)的用法如下。

(async function () {
  for await (const line of readLines(filePath)) {
    console.log(line);
  }
})()

異步 Generator 函數(shù)可以與for await...of循環(huán)結(jié)合起來使用。

async function* prefixLines(asyncIterable) {
  for await (const line of asyncIterable) {
    yield '> ' + line;
  }
}

異步 Generator 函數(shù)的返回值是一個(gè)異步 Iterator,即每次調(diào)用它的next方法,會(huì)返回一個(gè) Promise 對(duì)象,也就是說,跟在yield命令后面的,應(yīng)該是一個(gè) Promise 對(duì)象。

async function* asyncGenerator() {
  console.log('Start');
  const result = await doSomethingAsync(); // (A)
  yield 'Result: '+ result; // (B)
  console.log('Done');
}

const ag = asyncGenerator();
ag.next().then({value, done} => {
  // ...
})

上面代碼中,agasyncGenerator函數(shù)返回的異步 Iterator 對(duì)象。調(diào)用ag.next()以后,asyncGenerator函數(shù)內(nèi)部的執(zhí)行順序如下。

  1. 打印出Start。
  2. await命令返回一個(gè) Promise 對(duì)象,但是程序不會(huì)停在這里,繼續(xù)往下執(zhí)行。
  3. 程序在B處暫停執(zhí)行,yield命令立刻返回一個(gè) Promise 對(duì)象,該對(duì)象就是ag.next()的返回值。
  4. Aawait命令后面的那個(gè) Promise 對(duì)象 resolved,產(chǎn)生的值放入result變量。
  5. B處的 Promise 對(duì)象 resolved,then方法指定的回調(diào)函數(shù)開始執(zhí)行,該函數(shù)的參數(shù)是一個(gè)對(duì)象,value的值是表達(dá)式'Result: ' + result的值,done屬性的值是false。

A 和 B 兩行的作用類似于下面的代碼。

return new Promise((resolve, reject) => {
  doSomethingAsync()
  .then(result => {
     resolve({
       value: 'Result: '+result,
       done: false,
     });
  });
});

如果異步 Generator 函數(shù)拋出錯(cuò)誤,會(huì)被 Promise 對(duì)象reject,然后拋出的錯(cuò)誤被catch方法捕獲。

async function* asyncGenerator() {
  throw new Error('Problem!');
}

asyncGenerator()
.next()
.catch(err => console.log(err)); // Error: Problem!

注意,普通的 async 函數(shù)返回的是一個(gè) Promise 對(duì)象,而異步 Generator 函數(shù)返回的是一個(gè)異步 Iterator 對(duì)象??梢赃@樣理解,async 函數(shù)和異步 Generator 函數(shù),是封裝異步操作的兩種方法,都用來達(dá)到同一種目的。區(qū)別在于,前者自帶執(zhí)行器,后者通過for await...of執(zhí)行,或者自己編寫執(zhí)行器。下面就是一個(gè)異步 Generator 函數(shù)的執(zhí)行器。

async function takeAsync(asyncIterable, count = Infinity) {
  const result = [];
  const iterator = asyncIterable[Symbol.asyncIterator]();
  while (result.length < count) {
    const {value, done} = await iterator.next();
    if (done) break;
    result.push(value);
  }
  return result;
}

上面代碼中,異步 Generator 函數(shù)產(chǎn)生的異步遍歷器,會(huì)通過while循環(huán)自動(dòng)執(zhí)行,每當(dāng)await iterator.next()完成,就會(huì)進(jìn)入下一輪循環(huán)。一旦done屬性變?yōu)?code>true,就會(huì)跳出循環(huán),異步遍歷器執(zhí)行結(jié)束。

下面是這個(gè)自動(dòng)執(zhí)行器的一個(gè)使用實(shí)例。

async function f() {
  async function* gen() {
    yield 'a';
    yield 'b';
    yield 'c';
  }

  return await takeAsync(gen());
}

f().then(function (result) {
  console.log(result); // ['a', 'b', 'c']
})

異步 Generator 函數(shù)出現(xiàn)以后,JavaScript 就有了四種函數(shù)形式:普通函數(shù)、async 函數(shù)、Generator 函數(shù)和異步 Generator 函數(shù)。請(qǐng)注意區(qū)分每種函數(shù)的不同之處?;旧?,如果是一系列按照順序執(zhí)行的異步操作(比如讀取文件,然后寫入新內(nèi)容,再存入硬盤),可以使用 async 函數(shù);如果是一系列產(chǎn)生相同數(shù)據(jù)結(jié)構(gòu)的異步操作(比如一行一行讀取文件),可以使用異步 Generator 函數(shù)。

異步 Generator 函數(shù)也可以通過next方法的參數(shù),接收外部傳入的數(shù)據(jù)。

const writer = openFile('someFile.txt');
writer.next('hello'); // 立即執(zhí)行
writer.next('world'); // 立即執(zhí)行
await writer.return(); // 等待寫入結(jié)束

上面代碼中,openFile是一個(gè)異步 Generator 函數(shù)。next方法的參數(shù),向該函數(shù)內(nèi)部的操作傳入數(shù)據(jù)。每次next方法都是同步執(zhí)行的,最后的await命令用于等待整個(gè)寫入操作結(jié)束。

最后,同步的數(shù)據(jù)結(jié)構(gòu),也可以使用異步 Generator 函數(shù)。

async function* createAsyncIterable(syncIterable) {
  for (const elem of syncIterable) {
    yield elem;
  }
}

上面代碼中,由于沒有異步操作,所以也就沒有使用await關(guān)鍵字。

yield* 語(yǔ)句

yield*語(yǔ)句也可以跟一個(gè)異步遍歷器。

async function* gen1() {
  yield 'a';
  yield 'b';
  return 2;
}

async function* gen2() {
  // result 最終會(huì)等于 2
  const result = yield* gen1();
}

上面代碼中,gen2函數(shù)里面的result變量,最后的值是2。

與同步 Generator 函數(shù)一樣,for await...of循環(huán)會(huì)展開yield*。

(async function () {
  for await (const x of gen2()) {
    console.log(x);
  }
})();
// a
// b
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 異步編程對(duì)JavaScript語(yǔ)言太重要。Javascript語(yǔ)言的執(zhí)行環(huán)境是“單線程”的,如果沒有異步編程,根本...
    呼呼哥閱讀 7,399評(píng)論 5 22
  • 簡(jiǎn)單介紹下這幾個(gè)的關(guān)系為方便起見 用以下代碼為例簡(jiǎn)單介紹下這幾個(gè)東西的關(guān)系, async 在函數(shù)聲明前使用asyn...
    _我和你一樣閱讀 21,476評(píng)論 1 24
  • 弄懂js異步 講異步之前,我們必須掌握一個(gè)基礎(chǔ)知識(shí)-event-loop。 我們知道JavaScript的一大特點(diǎn)...
    DCbryant閱讀 2,867評(píng)論 0 5
  • 本文為阮一峰大神的《ECMAScript 6 入門》的個(gè)人版提純! babel babel負(fù)責(zé)將JS高級(jí)語(yǔ)法轉(zhuǎn)義,...
    Devildi已被占用閱讀 2,122評(píng)論 0 4
  • 在此處先列下本篇文章的主要內(nèi)容 簡(jiǎn)介 next方法的參數(shù) for...of循環(huán) Generator.prototy...
    醉生夢(mèng)死閱讀 1,486評(píng)論 3 8

友情鏈接更多精彩內(nèi)容