2016-04-27 49 views
2

我读过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 ...为什么?

回答

3

您可以将参数传递给timer所调用的函数,但不是您尝试的方式。

您需要将这些参数传递给setTimeoutitself

var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]); 


function request(time) { 
    let rand = Math.random()*10; 
    console.log(`rand is ${rand}`); 
    setTimeout(function(rand){ 
     it.next(rand) 
    }, time, rand); 
} 

但您的情况没有必要。在内部函数范围内可以访问rand

function request(time) { 
    let rand = Math.random()*10; 
    console.log(`rand is ${rand}`); 
    setTimeout(function(){ 
     it.next(rand); 
    }, time); 
} 
1

你有两个rand变量代码:

let rand = Math.random()*10; 
// ^^^^ 
… 
setTimeout(function(rand) { 
//     ^^^^ 
    … 
}, time); 

该函数的参数声明的影子外范围的一个第二个变量。由于回调函数未传递任何参数,因此其值为undefined - 这就是您传递给next的内容。

只要不声明该参数,并且外部rand将在闭包中的回调中可用。