1

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).

1
  • look into util.promisify Commented Jul 14, 2021 at 6:20

1 Answer 1

2

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);

    })
  })
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.