[英]how to use co.wrap with generator
const co = require('co');
const func1 = function(){
setTimeout(()=>{
console.log('func1');
},2000);
}
const func2 = function(){
setTimeout(()=>{
console.log('func2');
},2000);
}
const func3 = function(){
console.log('func3');
}
const gen = co.wrap(function*(){
yield func1;
yield func2;
return yield func3;
});
gen()
.then(function(){console.log('end')});
The expected result is func1 func2 func3 end 预期的结果是func1 func2 func3 end
but it doesn't show what I intended. 但这并没有显示我的意图。
It is showing func1 它显示func1
How can I fix the code to output the expected result 如何修复代码以输出预期结果
Two issues: 两个问题:
There's no way for your functions to return control. 您的函数无法返回控制。 If you want to use thunks (which the documentation advises against), you need to actually take and invoke a callback: 如果要使用thunk( 文档建议这样做),则需要实际使用并调用回调:
const func1 = function(cb){ setTimeout(()=>{ console.log('func1'); return cb(); },2000); };
However, it's better to use promises: 但是,最好使用诺言:
const func2 = function(){ return new Promise((resolve) => { setTimeout(()=>{ console.log('func2'); return resolve(); },2000); }); };
If you use promises, you need to invoke the function when you yield it: 如果使用promise,则需要在产生它时调用该函数:
yield func2();
You can only yield
a function without calling it if it's a thunk. 如果它很笨拙,则只能yield
一个函数而不调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.