Skip to content
Advertisement

How can I resolve or reject a promise based on a another promise?

function process () {
 return new Promise((resolve, reject) => {


    //make sure module exists
    let module = modules[queueData.module];
    if (!module) reject('module not found: '+queueData.module);

    //make sure processor exists
    let processor = fileProcessors[module.type];
    if (!processor) reject('processor not found: '+module.type);

      return anotherPromiseFunction();
})
}

processFile().catch(e => console.error)

anotherPromiseFunction() returns a promise. normally inside a .then() I can return a promise to make the then() wait for that promise to finish, but how do I do it when creating a promise?

Am I supposed to do this:

    anotherPromiseFunction()
        .then(e=>resolve(e))
        .catch(e=>reject(e))

That seems wrong…

Advertisement

Answer

You likely do not need the new Promise. The cases for “module exists” and “processor exists” can be handled separately, and then you can just return the call to anotherPromiseFunction after them:

//make sure module exists
let module = modules[queueData.module];
if (!module) {
  return Promise.reject(new Error('module not found: '+queueData.module));
}

//make sure processor exists
let processor = fileProcessors[module.type];
if (!processor) {
  return Promise.reject(new Error('processor not found: '+module.type));
}

return anotherPromiseFunction();

If the enclosing function is an async function, you can just throw the errors instead:

async function run() {
  //make sure module exists
  let module = modules[queueData.module];
  if (!module) {
    throw new Error('module not found: '+queueData.module);
  }

  //make sure processor exists
  let processor = fileProcessors[module.type];
  if (!processor) {
    throw new Error('processor not found: '+module.type);
  }

  return anotherPromiseFunction();
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement