Search code examples
javascriptnode.jspromisebluebird

NodeJS Promise, delaying return value


I am relatively new to NodeJS and JavaScript, but not programming.

I'm looking to return an array of objects after two SSH commands are executed via SSH2 and the output of the commands in the shell has been parsed. I have tried various Promises and examples I have found online, but to no avail. It seems that they just return the empty array without even waiting for the commands to execute. I am looking for any samples or a point in the right direction.

return Promise.resolve().then(function() {
  devicesAndScenes = [];
  executeCommand(JSON.stringify(getDeviceJson));
  executeCommand(JSON.stringify(getSceneJson));
}).then(sleep(2000)).then(function() {
  return devicesAndScenes;
});

function sleep(time) {
  return new Promise(resolve => {
    setTimeout(resolve, time)
  })
}

Solution

  • The problem is that the second .then (the one with the sleep() function) is not returning a promise, therefore it's resolving instantly and not waiting the specified time before executing the last .then

    return Promise.resolve()
    .then(() => {
      /* ... */
    })
    .then(() => {
      /* your problem was here, if we add a return it should work properly */
      return sleep(2000)
    })
    .then(() => {
      /* now this wil be executed after the 2000s sleep finishes */
    });
    

    *Used bracket syntax in the arrow functions to make them a little bit more clear.