我读过David Walsh关于在异步任务中使用生成器的文章(https://davidwalsh.name/async-generators),我想做同样的事情。 这里是我的代码:ES6:在异步调用中使用生成器
function request(time) {
let rand = Math.random()*10;
console.log(`rand is ${rand}`);
setTimeout(function(rand){
it.next(rand)
}, time);
}
function *main() {
let result1 = yield request(5);
result1 = parseInt(result1);
let result2 = yield request(result1);
console.log(`result1 is ${result1} and result2 is ${result2}`);
}
let it = main();
it.next();
但在控制台中,我可以看到
rand is 6.367766260304355
rand is 0.3009188563265597
result1 is NaN and result2 is undefined
至于当脚本达到让兰特=的Math.random()* 10首次值为我可以看到保存在rand中,但是然后它进入setTimeout但不进入,但在脚本结尾处到达it.next(),然后返回到setTimeout的内部,但这次rand未定义。 这是为什么?我如何保存rand的值并将其传递给result1?
编辑: OK,当我编辑
function request(time) {
setTimeout(function(){
let rand = Math.random()*10;
console.log(`rand is ${rand}`);
it.next(rand)
}, time);
}
它工作正常。似乎我不能传递一个值setTimeout ...为什么?