node.js - Babel 将异步到模块方法转换为带有 ES6 映射的 Bluebird

标签 node.js ecmascript-6 babeljs bluebird

我们尝试将 Node.js 6.5.0 与 Babel 结合使用,使异步函数使用 Bluebird 而不是 native V8 ES6 Promise :

我们的package.json仅包含以下Babel条目:

"devDependencies": {
  "babel-cli": "^6.9.0",
  "babel-plugin-transform-async-to-module-method": "^6.8.0",
  "babel-plugin-transform-es2015-destructuring": "^6.9.0",
  "babel-plugin-transform-es2015-modules-commonjs": "^6.14.0",
}

.babelrc:

{
  "plugins": [
    "transform-es2015-modules-commonjs",
    "transform-es2015-destructuring",
    [
      "transform-async-to-module-method",
      {
        "module": "bluebird",
        "method": "coroutine"
      }
    ]
  ]
}

但是,我们返回 ES6 map 的异步函数在执行过程中会导致以下错误:

A value [object Map] was yielded that could not be treated as a promise

我们如何解决这个问题?

附注当使用 transform-async-to-generator异步函数转换为生成器时,一切正常

最佳答案

下面是一些触发相同错误的示例代码:

function giveMap() {
  return new Map();
}

void async function() {
  await giveMap();
}();

请注意,giveMap 未标记为async(这是实际问题)。

此代码将在使用 transform-async-to-generator 时运行,因为 Map 可以从生成器生成:

function* () {
  yield new Map();
}

但是,当使用transform-async-to-module-method时,我认为代码变得类似于这样:

Promise.coroutine(function* () {
  yield new Map();
});

这将导致错误,as explained here ,因为 Promise.coroutine() 期望产生 Promise。

因此,您应该留意返回 Map、已 await 开启但未映射 async 的函数.

关于node.js - Babel 将异步到模块方法转换为带有 ES6 映射的 Bluebird,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39463923/

相关文章:

node.js - 使用 Sails.js Waterline 跨多个模型进行高效查询

javascript - Es6 箭头函数转普通js

javascript - 并行调用 async/await 函数

javascript - 检测 ES2015 代码是由 babel 转译的还是本地运行的?

javascript - Node JS 图像代理

node.js - npm install firebase 失败

node.js - 如何解决错误: spawn EACCES on Jenkins when running Karma?

javascript - 使用属性类进行多次调用的 typescript

javascript - 在JS中创建一个新的类实例

javascript - 如果同名的 'let' 被使用两次(在 for 循环中),Babel 会重新声明函数参数