Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay() in the q module

Tags:

node.js

promise

q

I am using nodejs and learning promises using the q module.

I'm misunderstanding the delay() fn in the q module, I think .

When I run this code:

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);});

I expect to see delays of the indicated times.
The first delay seems to occur.
The second delay doesn't really seem to be 5500ms.
The third delay, expected 4500ms, doesn't seem to happen at all.

I am understanding "delay(x)" to mean "then, delay for x milliseconds". Is this incorrect? Am I misunderstanding?

If I modify the code to replace each delay(x) with

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

...then it works as I expect.

Can someone please explain? Thanks.

like image 811
Cheeso Avatar asked Mar 08 '26 08:03

Cheeso


1 Answers

The delay() is a little different than what anyone else would expect, which makes it uglier to chain them. I learned it from the discussion 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);});

Hopefully they will fix it soon.

like image 75
user568109 Avatar answered Mar 09 '26 20:03

user568109