0

I try to use sonos (https://www.npmjs.org/package/sonos) to return an array of the players i have on my network. I would like to use the sonos.search function to find players for me at startup and afterwards update the array with new players if connected to the network.

Since sonos.search is asynchronous the rest of the code will execute before all players are added to the array at startup. How can I block the code to run the sonos.search once for 10 seconds at startup building an array of players that is on the network and then liste/search for new players and add to array if connected?

-

James Bund
  • 183
  • 2
  • 14

2 Answers2

2

Trying to go against the asynchronous behavior of nodejs is generally not the best approach to a problem.

If you want the rest of your code to be executed after sonos has loaded the players, it should be called from within the callback of the asynchronous function.

If you really want to wait 10 seconds before launching the rest of your code though, you can use the setTimeout() function.

setTimeout(function() {
    codeToBeExecutedAfter10Secs();
}, 10000);
ploutch
  • 1,204
  • 10
  • 12
0

You can try :

https://github.com/luciotato/waitfor

to make sync call. It works with fibers and has many method to "wait" for something.

EDIT : a little example of using it assuming you use mongoskin to access data

var wait =require('wait.for');

wait.launchFiber(function(){
    var obj = getAsyncData();
});

function getAsyncData(){
   return wait.forMethod(db.collection('data'), 'find');
}

And I think MeteorJS framework use this library to handle sync functions.

mfrachet
  • 8,772
  • 17
  • 55
  • 110