gpt4 book ai didi

node.js - Node 从 Q.async 返回生成值

转载 作者:太空宇宙 更新时间:2023-11-03 22:54:56 25 4
gpt4 key购买 nike

使用这段代码:

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);
});

我期望 resultfoo() 的结果(即 'foo'),但它实际上是实际的生成器对象!

我在这里错过了什么或者我不明白什么?

** 解决方案 **

虽然答案是很好的解决方案,但我认为我什至可以通过简单地这样做来缩短整个过程

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

最佳答案

async 是一个生成器函数装饰器。任何您打算用作 Promise 蹦床的函数都必须经过修饰。另外,我选择将 this 上下文作为 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);
});

关于node.js - Node 从 Q.async 返回生成值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22110343/

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