Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Promises Run Without Being Called

When using promises, they run automatically without being called. I followed the MDN Docs on setting them up, and they run when they are declared, without being prompted.

var progressPromise = new Promise(function(resolve, reject) {
  // Query the DB to receive the ToDo tasks
  // inProgress is the tableID

  getTasks(inProgress, function(tasks) {
    // Check that the list is returned.
    console.log("Shouldn't Run Automatically");
    if (tasks) {
      console.log("This Too Runs Automatically");
      resolve(tasks);
    } else {
      reject("There was a failure, the data was not received");
    }
  });

});
<p>Console Output</p>
<p> Shouldn't Run Automatically </p>
<p> This too runs automatically </p>

I've checked the remaining code, only the promises trigger when I start the app with node index.js

Is this by design, or is my implementation wrong? If it's by design it would be great if you could link me to the docs, because I was unable to find anything on it.

Thank you!

like image 553
Julian E. Avatar asked Dec 19 '22 02:12

Julian E.


1 Answers

...and they run when they are declared, without being prompted

You don't "declare" promises. new Promise creates a promise and calls the executor function you pass it, synchronously, before new Promise returns. You do that when you want the work the executor does to be started (right then), not later.

If you want to define something that will do something returning a promise but not start it yet, simply put it in a function:

// Explicit promise creation (only when necessary)
function doProgress() {
    return new Promise(function(resolve, reject) {
        // ...
    });
}

// Or an `async` function, which always returns a promise
async function doProgress() {
    // ...code using `await` on other promises/thenables here...
}

...then call it when you want that process to begin:

var progressPromise = doProgress();

Documentation:

  • Using Promises on MDN
  • Promise on MDN
  • Promise Objects in the specification
like image 185
T.J. Crowder Avatar answered Dec 20 '22 17:12

T.J. Crowder