8. mkdir async-test && cd $_
npm init
npm i -D babel-cli
npm i -D babel-polyfill
npm i -D babel-preset-es2015
npm i -D babel-preset-stage-3
babelのセットアップ
15. for … of 文
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/for...of
16. 検証コード2
for…ofでawaitを繰り返す
import 'babel-polyfill';
function sleep(count) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(count);
}, count*1000);
});
}
async function Main() {
let times = [1, 2, 3];
for (let t of times) {
let time = await sleep(t);
console.log(time.toString() + ' times.');
}
}
Main();
18. 実行すると怒られた。
$ node test.js
/Users/btf/src/node.js/async-await-for/test.js:4
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee() {
^
ReferenceError: regeneratorRuntime is not defined
at /Users/btf/src/node.js/async-await-for/test.js:4:32
at Object.<anonymous> (/Users/btf/src/node.js/async-await-for/test.js:83:2)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
ぐぐってみるとbabel-polyfillが効いてない感じ。
19. test.jsを開いてみる
'use strict';
var Main = function () {
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee()
{
var times, _iteratorNormalCompletion, _didIteratorError, _iteratorError,
_iterator, _step, t, time;
return regeneratorRuntime.wrap(function _callee$(_context) {
…(中略)…
require('babel-polyfill');
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this,
arguments); return new Promise(function (resolve, reject) { function
step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch
(error) { reject(error); return; } if
Main()の後にbabel-polyfillを呼んでる。
なんで?babelのバグ?
20. とりあえず手で直してみた。(本題とは関係ないので)
'use strict';
require('babel-polyfill');
var Main = function () {
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee()
{
var times, _iteratorNormalCompletion, _didIteratorError, _iteratorError,
_iterator, _step, t, time;
return regeneratorRuntime.wrap(function _callee$(_context) {
…(省略)…