节点返回从Q.async产生的值

有了这段代码:

function * foo(ctx) { // process some things // yield some async stuff... return 'foo'; } Q.async(function * (ctx) { return yield foo(ctx); })(this).done(function(result) { console.log(result); }); 

我期望的结果是foo() (即'foo' )的结果,但它是实际的发电机对象!

我在想什么,或者我在这里不明白?

**解决scheme**

虽然答案是很好的解决办法,但我觉得我甚至可以通过简单的做法来缩短整个事情

 result = Q.async(foo)(this); 

async是一个生成器函数装饰器。 您打算用作承诺蹦床的任何function都必须进行装饰。 另外,我也select了this背景。

 var foo = Q.async(function *() { // yield, yield, yield return "foo"; }); var bar = Q.async(function *() { // yield, yield, yield return foo.call(this); }); bar.call(this).done(function (result) { console.log(result); }); 

主要的问题是你需要这样做:

 return yield* foo(ctx); 

你之前所称的return yield foo(ctx) 。 这将做foo(ctx)创build一个发电机,然后yield ...将产生发电机。 由于发电机不是保证,所以Q将认为它已经解决,并使发电机的发电成果。 然后返回yield的结果,所以async函数产生一个生成器对象。 通过添加* ,您告诉生成器接pipe而不是产出,因此yield* foo(ctx)的结果实际上是foo而不是返回foo的生成器。

我在本地遇到的第二个问题(如果你在foo中有实际的asynchronous代码,你可能不会),如果foo生成器是同步的而不是asynchronous的,它会立即返回foo而不是返回一个parsing为foo的promise,所以.done函数不存在。