2016-04-27 36 views
2

非同期タスク(https://davidwalsh.name/async-generators)でジェネレータを使用する方法についてDavid Walshの記事を読んで、同じことをしたかったのです。 は、ここに私のコードです: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(); 

が、コンソールに、私は最初の時間値のために限り、スクリプトがランド= Math.random(聞かせて到達したときに、私が見ることができるように

rand is 6.367766260304355 
rand is 0.3009188563265597 
result1 is NaN and result2 is undefined 

)* 10を見ることができるのですrandに保存されますが、setTimeoutに移動しますが、スクリプトの最後には入りませんが、it.next()に到達してsetTimeoutの内側に戻りますが、この時間は未定義です。 なぜですか?どのようにしてrandの価値を保存し、result1に渡すことができますか?

編集: OK、私はそれが正常に動作します

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

を編集しました。 setTimeoutに値を渡すことができないようです...なぜですか?

答えて

3

タイマーによって呼び出された関数に引数を渡すことはできますが、試行した方法には渡すことはできません。

これらの引数を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にアクセスできます。あなたはあなたのコード内の2つの変数rand持っ

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

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

をその関数のパラメータは、外側のスコープから1をシャドウ秒の変数を宣言します。コールバック関数に引数が渡されないので、その値はundefinedです。これがnextに渡しています。

このパラメータは宣言しておらず、外側のrandはクロージャによってコールバックで利用できるようになります。

関連する問題