我们尝试将 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/