gpt4 book ai didi

javascript - Bluebird 协程使用

转载 作者:IT老高 更新时间:2023-10-28 23:02:44 26 4
gpt4 key购买 nike

我正在尝试如下使用 Bluebird 的协程:

var p = require('bluebird');
//this should return a promise resolved to value 'v'
var d = p.coroutine(function*(v) { yield p.resolve(v); });
//however this prints 'undefined'
d(1).then(function(v){ console.log(v); });

这里有什么不正确的地方?

最佳答案

引用 documentation of coroutine ,

Returns a function that can use yield to yield promises. Control is returned back to the generator when the yielded promise settles.

所以,函数可以使用yield,但yield不用于从函数返回值。无论您使用 return 语句从该函数返回什么,都将是协程函数的实际解析值。

Promise.coroutine 只是让 yield 语句等待 Promise 解决,实际的 yield 表达式将被评估为解析值。

在你的情况下,表达式

yield p.resolve(v);

将被评估为 1 并且由于您没有从函数显式返回任何内容,默认情况下,JavaScript 返回 undefined。这就是为什么你会得到 undefined 作为结果。


要解决这个问题,您实际上可以像这样返回产生的值

var p = require('bluebird');

var d = p.coroutine(function* (v) {
return yield p.resolve(v);
});

d(1).then(console.log);

关于javascript - Bluebird 协程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30960764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com