Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Wait in Node.js

Here is a question about what I would think would be a simple pattern in node js.

Here is my example in coffeescript:

db_is_open = false

db.open ->
  db_is_open = true

wait = ->
wait() until db_is_open

And here again in javascript:

var db_is_open = false;

db.open(function() {
  db_is_open = true;
});

function wait() {};
while (not db_is_open) { wait()};

This does not work at all because the while loop never relinquishes control, which I guess makes sense. However how can I tell the wait function to try the next callback in the queue?

like image 852
Brad C Avatar asked Jan 16 '12 15:01

Brad C


People also ask

How do I wait in NOdeJS?

One way to delay execution of a function in NodeJS is to use the seTimeout() function. Just put the code you want to delay in the callback. For example, below is how you can wait 1 second before executing some code.

How do you wait 1 second in JavaScript?

To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.

How do I pause a NOdeJS script?

Using Async/Await to Delay a Node. js Program. An await expression causes execution to pause until a Promise is resolved.


2 Answers

I like to use the async module when I have bits of code that need to run synchronously.

var async = require('async');

async.series([
  function(next){
    db.open(next)
  }
, function(next){
    db.loadSite('siteName', next)
  }
], function(err){
  if(err) console.log(err)
  else {
    // Waits for defined functions to finish
    console.log('Database connected')
  }
})
like image 135
Pastor Bones Avatar answered Oct 19 '22 16:10

Pastor Bones


Why are you waiting, and not just using a callback that runs inside of the function passed to db.open? This is pretty much idiomatic Node code:

db.open(function() {
  // db is now open, let's run some more code
  execute_db_query();
});

Basically, you should simply follow the patterns laid out in the documentation.

like image 31
Matt Ball Avatar answered Oct 19 '22 17:10

Matt Ball