简体   繁体   中英

How to wait for a function that calls another callback function - JavaScript

I am using a third party library function that uses callback . I wish it used Promise instead. I can't seem to figure out how I can wait for a callback to happen before I can return something from a function.

// this is the third party function that I cannot change
const callbackFunction = (arg: string, callback: (err?: string, result?: string) => void) => {
    console.log("do something else");
    return callback(undefined, "some data");
}

I want to write a function that gets the result for me. This is what I have so far, but does not seem like a right approach.

This is my function, which should return result

const someFunction = (): string | undefined => {
    console.log("do something async"); // async/await
    callbackFunction("something", (err, result) => {
        return result || undefined;
    });

    // how to return `result` from here?
}

I wish it used Promise instead.

You can take a callback-based api and wrap it in a promise using the new Promise constructor.

const someFunction = (): Promise<string | undefined> => {
  return new Promise((resolve, reject) => {
    console.log('do something');
    callbackFunction('something', (err, result) => {
      if (err) 
        reject(err);
      else 
        resolve(result || undefined);
    });
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM