7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.js v7 で async/awaitを試してみる

Posted at

背景

Node.js v7が Nightly build で使えるようになり、 async/await も使えるようになっていたのでメモ

Nightly buildとは...
http://www.sophia-it.com/content/%E3%83%8A%E3%82%A4%E3%83%88%E3%83%AA%E3%83%BC%E3%83%93%E3%83%AB%E3%83%89

Node.js v7 の nvm インストール

nvm install 7

もしかすると、下記のようなエラーが出るかも。
その場合、nvm use --delete-prefix v7.0.0-nightly20161020d62e7bd1f9を実行してください。

nvm is not compatible with the npm config "prefix" option: currently set to "/usr/local/Cellar/nvm/0.31.2/versions/node/v7.0.0-nightly20161020d62e7bd1f9"
Run `npm config delete prefix` or `nvm use --delete-prefix v7.0.0-nightly20161020d62e7bd1f9` to unset it.

async/awaitを含んだコードの実行

下記のコードを保存し、
node --harmony-async-await app.js で実行すると、

  • スタート と出力
  • 約1秒待つ
  • 途中 と出力
  • 約1秒待つ
  • 終わり と出力

といった挙動を見せてくれます。

※ 今のところ --harmony-async-await というオプションを付けないと動きません

app.js
const wait = (delay) => {
  return new Promise(resolve => setTimeout(resolve, delay));
}

async function tryWaitFunction () {
  console.log('スタート')
  await wait(1000);
  console.log('途中')
  await wait(1000);
  console.log('終わり')
}

tryWaitFunction();
7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?