在过去的几个小时里,我完全陷入了这个困境。
如何将参数传递给生成器函数?
function* getFoo(foo) {
return yield Promise.resolve(foo + 10);
}
exports.testRoute = Promise.coroutine(function* (req, res) {
let bar = yield Promise.coroutine(getFoo); // <--- how to pass argument??
res.send(bar.toString());
});
当前代码抛出错误(我知道它指向 here 但它没有说明任何有关参数传递的信息):
Unhandled rejection TypeError: A value [object Promise] was yielded that could not be treated as a promise
See http:// goo.gl/4Y4pDk
From coroutine:
at Function.module.exports.Promise.coroutine (d:\Workspace\Github\API-NodeJS\app\node_modules\bluebird\js\main\generators.js:111:17)
如果我这样做:
let bar = yield Promise.coroutine(getFoo(5));
我收到以下错误(又是不言自明的错误,但 this link 也没有解释参数传递):
Unhandled rejection TypeError: generatorFunction must be a function
See http:// goo.gl/6Vqhm0
at Function.module.exports.Promise.coroutine (d:\Workspace\Github\API-NodeJS\app\node_modules\bluebird\js\main\generators.js:107:15)
最佳答案
我相信你想要的是这样的:
function* getFoo(foo) {
return yield Promise.resolve(foo + 10);
}
exports.testRoute = Promise.coroutine(function* (req, res) {
let bar = yield Promise.coroutine(getFoo)(50);
res.send(bar.toString());
});
您需要了解什么Promise.coroutine
做。它需要一个生成器并返回一个返回 promise 的函数。
正如您在第一种情况中看到的那样(yield Promise.coroutine(getFoo);
),您将生成 Promise.coroutine
的结果,它是一个函数,而不是一个 promise ,这会导致错误:
A value [object Promise] was yielded that could not be treated as a promise
在第二种情况下(yield Promise.coroutine(getFoo(5));
),您只是启动生成器。 getFoo(5)
返回一个“生成器”对象,但 Promise.coroutine
想要一个“生成器函数”,这会导致:generatorFunction 必须是一个函数
.
事实上,bluebird 将 Promise.coroutine 的结果显示为 [object Promise]
造成了很大的困惑,因为 Promise.coroutine 应该返回一个函数,但我无法理解它出去。我想你可以把它作为另一个问题来问。
关于javascript - 将参数传递给生成器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41268979/