2016-08-06 25 views
1

我有這樣的代碼:如何訪問setTimeout中的值?

function* showValue() { 
    setTimeout(function*() { 
    console.log('yielding') 
    return yield 100; 
    }, 1000); 
} 

var valFunc = showValue(); 
console.log(valFunc.next()); 

當我運行它,我看到這樣的輸出:

{ value: undefined, done: true } 

爲什麼我應該做有.next()調用返回100?

+0

'setTimeout'是異步的,它完成在稍後的時間,因此你不能僅僅從它返回。在你的情況下,你可能需要一個回調或一個承諾,以知道計時器什麼時候完成它的事情。 – adeneo

+0

沒錯,我可能還沒有理解發現者,但我一直在想,如果'showValue'得到暫停,從某個地方產生,即使在setTimeout內部,也會恢復執行。 – Geo

+0

setTimeout將不會返回除id號之外的其他任何內容,但作爲setTimeout回調函數提供的匿名生成器函數將在時間到期時運行,並且它返回的生成器對象將丟失。您必須在setTimeout內捕獲它,然後相應地使用它。 – Redu

回答

1

您可能會考慮如下更改代碼;

function showValue() { 
 
    return setTimeout(function() { function* gen() { 
 
            console.log('yielding'); 
 
            yield 100; 
 
           } 
 
           var it = gen(); 
 
           console.log(it.next().value); 
 
           }, 1000); 
 
} 
 
showValue();    // will display result after 1000+ms 
 
console.log(showValue()); // will immediately display setTimeout id and after 1000+ms will display the generator yielded value again.

+0

如何修改這個值,以便在運行'console.log(showValue())'時可以看到這個值? – Geo

+1

不可能。 setTimeout是一個異步函數。當你調用showValue時,它會調用setTimeout,並且需要一些時間來做一些事情(它不會返回除id之外的任何東西)。在調用console.log(setTimeout())的時刻,生成器函數仍在等待放入事件隊列中,並在稍後至少1000毫秒內調用。所以你希望它執行的任何事情都必須鏈接到異步時間線上。我會修改代碼,希望您能夠理解事實。 – Redu