Node.js Promises Run Without Being Called

Viewed 1579

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!

2 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:

you can use promise like this in js

async function asyncfunc() {
    return new Promise((resolve, reject) => {
        yourFuncWithCallBack((data) => {
            if (data) {
                resolve(data)
            }
            reject(new Error('data did not exist'))
        });
    });
}

and use asyncFunction like this

try {
   var data = await asyncfunc();
   // do some thing with data
} catch (error) {
 // do some thing with error
}

if you want to use promise in typescript

interface ResolveDataType {
   // some property
}

async function asyncfunc():Promise<ResolveDataType> {
    return new Promise((resolve, reject) => {
        yourFuncWithCallBack((data:ResolveDataType) => {
            if (data) {
                resolve(data)
            }
            reject(new Error('data did not exist'))
        });
    });
}

and use asyncFunc like this

try {
   const data = await asyncfunc();
   // do some thing with data
} catch (error) {
 // do some thing with error
}
Related