异步生成器在 babel-node 上工作,但在 babel-register 或 build 上失败
Async Generator works on babel-node but fails w/ babel-register or build
使用 babel-node
我能够 运行 以下代码
function timeout(ms = 100) {
return new Promise(resolve => {
let id = setTimeout(() => {
clearTimeout(id)
resolve(ms)
}, ms)
})
}
async function* worker(limit = 10) {
async function fetch() {
return await timeout(Math.random() * 1000)
}
let low = 0;
while (low++ < limit) yield await fetch()
}
async function run() {
const gen = worker(5)
const results = [];
for await (const res of gen) {
console.log('working')
results.push(res)
}
return 'done'
}
run().then(res => console.log(res)).catch(err => console.error(err))
在这里不起作用,但在网上可以Babel REPL
以及当我 运行 它通过 babel-node
就像:
babel-node src/script.js
但是当我构建时它失败了并且运行它是这样的:
babel src/script.js --out-file dist/script.js
node dist/script.js
然后给我
TypeError: iterable[Symbol.iterator] is not a function
使用 babel-register
也失败并出现同样的错误:
node -r babel-register -r dotenv/config src/script.js
我现在的.babelrc
长得像
{
"plugins": ["transform-strict-mode", "transform-async-generator-functions"],
"presets": ["es2015-node6", "stage-2"]
}
使用 es2015
而不是 es2015-node6
没有产生任何好处
当我查看用于 babel-node
here 的默认插件和预设时,看起来它们是空的
我错过了什么?
babel-node
(和在线 REPL),除了处理运行时转译,还有 requires babel-polyfill。您应该 npm i -S babel-polyfill
然后 import 'babel-polyfill';
在您的程序的入口点(或者在您的示例中,将 -r babel-polyfill
添加到您的 node
args)。
使用 babel-node
我能够 运行 以下代码
function timeout(ms = 100) {
return new Promise(resolve => {
let id = setTimeout(() => {
clearTimeout(id)
resolve(ms)
}, ms)
})
}
async function* worker(limit = 10) {
async function fetch() {
return await timeout(Math.random() * 1000)
}
let low = 0;
while (low++ < limit) yield await fetch()
}
async function run() {
const gen = worker(5)
const results = [];
for await (const res of gen) {
console.log('working')
results.push(res)
}
return 'done'
}
run().then(res => console.log(res)).catch(err => console.error(err))
在这里不起作用,但在网上可以Babel REPL
以及当我 运行 它通过 babel-node
就像:
babel-node src/script.js
但是当我构建时它失败了并且运行它是这样的:
babel src/script.js --out-file dist/script.js
node dist/script.js
然后给我
TypeError: iterable[Symbol.iterator] is not a function
使用 babel-register
也失败并出现同样的错误:
node -r babel-register -r dotenv/config src/script.js
我现在的.babelrc
长得像
{
"plugins": ["transform-strict-mode", "transform-async-generator-functions"],
"presets": ["es2015-node6", "stage-2"]
}
使用 es2015
而不是 es2015-node6
没有产生任何好处
当我查看用于 babel-node
here 的默认插件和预设时,看起来它们是空的
我错过了什么?
babel-node
(和在线 REPL),除了处理运行时转译,还有 requires babel-polyfill。您应该 npm i -S babel-polyfill
然后 import 'babel-polyfill';
在您的程序的入口点(或者在您的示例中,将 -r babel-polyfill
添加到您的 node
args)。