Make Async Await Work In Promises

I have some issues with getting async and await working inside of Promise’s.

When using this code:

function returnSomething(name) {
  return new Promise((resolve, reject) => {
    const somethingElse = await returnSomethingElse();
    return resolve(somethingElse);
  });
}

I got this error

/app/app.js:63
      const something = await returnSomethingElse();
                              ^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier

I knew I needed to add async into the mix, so I was changing the function to

async function returnSomething(name) { // <--- this line
  return new Promise((resolve, reject) => {
    const somethingElse = await returnSomethingElse();
    return resolve(somethingElse);
  });
}

I also knew I needed a try...catch-statement, so I added it

async function returnSomething(name) {
  return new Promise((resolve, reject) => {
    try {
      const somethingElse = await returnSomethingElse();
      return resolve(somethingElse);
    } catch(error) {
      return reject(error);
    }
  });
}

But still no luck, then I realised I didn’t have an async function. The arrow function in the new Promise is not async! So I change the code to this and it worked:

function returnSomething(name) {
  return new Promise(async (resolve, reject) => { // <--- this line
    try {
      const somethingElse = await returnSomethingElse();
      return resolve(somethingElse);
    } catch(error) {
      return reject(error);
    }
  });
}

Happy coding! – Found a mistake or a typo? Please submit a PR to my GitHub-repo.

Like this post? Follow @harianus on Twitter