2013-07-18 55 views
3

我正在使用nodejs和使用q模塊學習promise。q模塊中的延遲()

我誤解了q模塊中的delay() fn,我想。

當我運行這段代碼:

chain 
    .then (function() {console.log('starting');}) 
    .then (function() {console.log('waiting 2500ms');}) 
    .delay(2500) 
    .then (function() {console.log('done');}) 
    .then (function() {console.log('waiting 5500ms');}) 
    .delay(5500) 
    .then (function() {console.log('done');}) 
    .then(function() {console.log('waiting 4500ms');}) 
    .delay(4500) 
    .then (function() {console.log('done');}) 
    .then(function() { process.exit(0);}); 

我希望看到的指定時間的延遲。
第一次延遲似乎發生。
第二次延遲似乎不是5500ms。
第三次延遲,預計爲4500ms,似乎根本沒有發生。

我在理解「delay(x)」意思是「那麼延遲x毫秒」。這是不正確的?我誤解了嗎?

如果我修改代碼來替換每個delay(x)

.then(function() {sleep.usleep(x * 1000);}) 

...然後它工作如我所料。

有人能解釋一下嗎? 謝謝。

+1

**警告**:此主題中的信息與Q的舊版本有關,因此不再準確。新版本的延遲工作方式與您期望的相同。 –

回答

7

delay()與其他人所期望的稍有不同,這使得它更難鏈鎖它們。我從討論中瞭解到here

Q() 
    .then (function() {console.log('starting');}) 
    .then (function() {console.log('waiting 2500ms');}) 
    //.delay(2500) 
    .then(function() { return Q().delay(2500); }) 
    .then (function() {console.log('done');}) 
    .then (function() {console.log('waiting 5500ms');}) 
    //.delay(5500) 
    .then(function() { return Q().delay(5500); }) 
    .then (function() {console.log('done');}) 
    .then(function() {console.log('waiting 4500ms');}) 
    //.delay(4500) 
    .then(function() { return Q().delay(4500); }) 
    .then (function() {console.log('done');}) 
    .then(function() { process.exit(0);}); 

希望他們能儘快解決。

+0

謝謝,很好的信息。 – Cheeso

+0

這實際上是在幾周前修復的(https://github.com/kriskowal/q/pull/326?source=cc)。嘗試確保您使用的是最新版本,我認爲0.9.6應該按照您的預期工作。 – ForbesLindesay

+0

嗯,我在0.9.6上。我報告的行爲發生在0.9.6 – Cheeso