简体   繁体   English

如何等待 function 调用另一个回调 function - JavaScript

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

I am using a third party library function that uses callback .我正在使用使用callback的第三方库 function 。 I wish it used Promise instead.我希望它改用Promise I can't seem to figure out how I can wait for a callback to happen before I can return something from a function.我似乎无法弄清楚如何等待回调发生,然后才能从 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.我想写一个 function 来为我得到result This is what I have so far, but does not seem like a right approach.这是我到目前为止所拥有的,但似乎不是一个正确的方法。

This is my function, which should return result这是我的 function,它应该返回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.我希望它改用 Promise。

You can take a callback-based api and wrap it in a promise using the new Promise constructor.您可以使用基于回调的 api 并使用new Promise构造函数将其包装在 promise 中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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