Search code examples
node.jsasync-awaites6-promise

async function resolve with Promise but returns undefined


I'm reading data from db with using await so I used Promise but the function seems to return nothing

async function read() {
  return new Promise((resolve, reject) => {
    const db = new DB();
  
    db
    .read()
    .then(result => {
      resolve(result);
    }).catch(() => {
      reject('db-error');
    });
  });
}

(async () => {
  const data = await read();

  console.log(data); // undefined
})();

How can I make read() return result?


Solution

  • You are making it more complicated than it has to be. If you are already using an API that returns a promise then there is no need to use the promise constructor yourself.

    And declaring a function as async is only necessary if you are using await in it to deal with promises.

    So either do:

    function read() {
      const db = new DB();
      return db
        .read()
        .catch(() => {
          return 'db-error';
        });
    }
    

    Or

    async function read() {
      const db = new DB();
      try {
        return await db.read();
      } catch(error) {
        return 'db-error';
      }
    }
    

    If you are still not getting the value you want then you are not using the database API correctly and you have to read its documentation to figure out how to get back the right data.