Search code examples
javascripttypescriptasynchronousasync-awaites6-promise

How can an async function await the callback of an inner async function?


I have an async function that must return when the callback of an inner async function returns. I cannot await that inner function because it does not return a promise. I've tried specifying await in passing the callback but that does not do the trick. As such:

async getPublicKey(): Promise<string> {

    const callback = async (err: any, key: any) => {
      if (!err) this.publicKey = key.result;
      else console.error(err);
    };

    this.web3js.currentProvider.sendAsync({
      jsonrpc: '2.0',
      method: 'eth_getEncryptionPublicKey',
      params: [this.account],
      from: this.account,
    }, callback);

    return this.publicKey
  }

Here, the goal is to return key.result of the callback function. However, we cannot await that callback and the sendAsync function returns immediately (cannot await it).


Solution

  • You'll want to wrap the callback in a new Promise and return the resolve or reject. This way, you can await your call to await getPublicKey() and it will not resolve until the callback is done.

    async getPublicKey(): Promise<string> => {
      return new Promise((resolve, reject) => {
        const callback = async (err: any, key: any) => {
          if (!err) {
              resolve(key.result);
          }
          else {
            reject(err);
          }
        };
    
        this.web3js.currentProvider.sendAsync({
          jsonrpc: '2.0',
          method: 'eth_getEncryptionPublicKey',
          params: [this.account],
          from: this.account,
        }, callback);
    
        })
      })
    }