Search code examples
javascriptasync-awaitecmascript-next

Resolving async function within internal callback


When explicitly returning a new Promise from a function we get resolve and reject functions passed in. We can use these methods inside our function at any point to indicate the resolution or rejection of the promise, including inside callbacks to other functions internally.

Consider:

const doSomeDbWork = function (db) {
   return new Promise((resolve, reject) => {
     db.doStuff(result => resolve(result));
   });
};

Is there an equivalent when using async without explicitly returning a new Promise when we can't also await (like in the case of this db callback)?

const doSomeDbWork = async function (db) {
  db.doStuff(result => /* ? */);
};

I'm currently thinking that this isn't possible and that I just need to return a new Promise. Have I missed a trick? Is there a way to do this?


Solution

  • Is there an equivalent when using async without explicitly returning a new Promise.

    No. async/await only works with promises (or thenables), and you have to promisify everything else yourself. In your case, that would most likely be something like

    async function doSomeDbWork(db) {
        return new Promise(db.doStuff);
    }
    

    or

    async function doSomeDbWork(db) {
         return new Promise(resolve => { db.doStuff(resolve); });
    }
    

    (possible with an await after the return).