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?
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.
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.
Using Async/Await to Delay a Node. js Program. An await expression causes execution to pause until a Promise is resolved.
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')
}
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With