蓝鸟协同使用

aut*_*con 15 javascript coroutine node.js promise bluebird

我试图使用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); });
Run Code Online (Sandbox Code Playgroud)

这里有什么不对?

the*_*eye 21

引用文档coroutine,

返回可用于yield产生promise 的函数.当产生的承诺结算时,控制权返回到发电机.

因此,该函数可以使用yield,但yield不用于从函数返回值.无论您从该函数返回的是什么,都return将是coroutine函数的实际解析值.

Promise.coroutine只需使yield语句等待解析的承诺,实际yield表达式将被计算为已解析的值.

在你的情况下,表达式

yield p.resolve(v);
Run Code Online (Sandbox Code Playgroud)

将被评估1,因为您没有显式返回任何函数,默认情况下,JavaScript返回undefined.这就是为什么你得到undefined的结果.


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

var p = require('bluebird');

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

d(1).then(console.log);
Run Code Online (Sandbox Code Playgroud)