admin管理员组

文章数量:1180494

I'm working with a third party library and I'm attempting to pass a callback returning a string to a method using their API, but the catch is the callback would need to be executed asynchronously in my case... I don't think this is possible, but I wanted to confirm.

The essential format of the third party library's method:

const MyPlugin = {
    push: (fn) => {
    const val = fn();
    console.log('val ' + val); // val must be a string returned by my internal API call
  }
}

MyPlugin.push() takes a callback parameter that needs to return a string (specifically, an encrypted token). However, I need to make an API call internally to have this token generated at the time when this third party method is called.

This callback function gets triggered on the third party's side when a certain event fires, and I'd like to avoid making my internal API call until this event fires... otherwise I'd simply generate the token outside of the third party method and then call the third party method once my API call resolves.

Of course, attempting to use a promise for the callback simply returns the promise itself, rather than returning the actual string generated by my API call. Due to the fact that I need to have my own API call run simultaneously with the third party's method, I don't think this is possible, but wanted to check in case I'm wrong and there's some kind of workaround. Thanks.

本文标签: javascriptPassing an asynchronous method as a callback returning a valueStack Overflow