Search code examples
node.jsbluebird

Promise.try without bluebird


I am trying to re-create bluebird's promise.try function, is this essentially the same?

function promiseTry(callback) {
  let error;
  let value;
  try {
    value = callback();
  } catch (e) {
    error = e;
  }
  return new Promise((resolve, reject) => {
    if (error) {
      reject(error);
      throw error;
    }
    resolve(value);
  });
}

const x = promiseTry(() => {
  throw new Error('hi');
});

How can I simply implement bluebird's Promise.try with a native node Promise?


Solution

  • This should be equivalent:

    function promiseTry(callback) {
      return new Promise((resolve, reject) => {
        try {
          resolve(callback())
        } catch(e) {
          reject(e);
        }
      });
    }
    
    const x = promiseTry(() => {
      throw new Error('hi');
    });
    
    x.then(() => console.log("Promise resolved")).catch(err => console.log("Promise rejected:", err.message));

    If you can use async/await, async functions have this behavior implicitly. Any synchronous exceptions thrown in an async function are converted into a promise rejection.