LegoGeo
LegoGeo

Reputation: 153

JS: Can reject be left out of promises?

With promises, is it bad practice to leave out the use of reject? If I just want to return a Promise to ensure this function is run in it's entirety and not block whatever follows this function.

function testFunc() {
     return new Promise((resolve,reject) => {
            // do stuff
            resolve(true);
     })
}

testfunc().then(() => { // additional stuff});

Upvotes: 2

Views: 70

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 371128

If there is a chance of the do stuff throwing an error, then you should make sure to use reject and call it in case there's an error, so that the caller can see that there was a problem and (hopefully) handle it appropriately. For example, you wouldn't want to do:

function testFunc() {
     return new Promise((resolve,reject) => {
            getApi((error, result) => {
                resolve(result);
            });
     });
}

but instead

function testFunc() {
     return new Promise((resolve,reject) => {
            getApi((error, result) => {
                if (error) reject(error);
                resolve(result);
            });
     });
}

If there's really no chance of the contents of the function erroring (barring logic bugs that could be unknowingly present in any code), then reject won't help you, because you don't really have any place suitable to put it. For example:

function someWeirdPromiseFunctionThatBlocks() {
     return new Promise((resolve) => {
         for (let i = 0; i < 1e5; i++) {
         }
         resolve();
     });
}

Note that if you just want to:

not block whatever follows this function.

then just returning a Promise won't accomplish that, because the Promise constructor will run all of its code synchronously until it encounters something asynchronous (like getApi). To avoid blocking the running of sync code below, use Promise.resolve or setTimeout, eg:

function testFunc() {
    return Promise.resolve()
        .then(() => {
            // do other stuff
        });

Upvotes: 1

Scotty Jamison
Scotty Jamison

Reputation: 13259

No, its not necessary at all. reject is meant to be used in a similar way as one might use throw - it's for errors that happen.

In fact, if you're familiar with javascript's async/await syntax, this async function...

async function doSomething() {
  throw new Error('Oh no!')
}

...roughly translates to this:

function doSomething() {
  return Promise.reject(new Error('Oh no!'))
}

which shows how reject is intended to be used wherever you might normally throw an error.

Here's an example promise that I use often where there isn't any "reject" that would make sense:

const wait = ms => new Promise(resolve => setTimeout(resolve, ms))

wait(1000).then(() => console.log('done'))

Many others such examples exist.

Upvotes: 0

Related Questions