-2

I'm using a table/grid js library that allows me to give it a function that will be called upon user right-click to display some data in a menu. The function's return type is Array<String>. However, I would like to perform an async action (load data from a network request) in my function and use its result in my function return value. How can I do this via callbacks or otherwise?

function getMenuItems(): Array<string>{

  const resp: Promise = asyncLoadData()
  //How can I use this async construct in my sync function???
  const items = ... //e.g. map resp into my return value.

  return items
}

To be clear, getMenuItems() is a parameter to a 3rd party library and i I cannot change the return value of it to accept a promise or change the method to be async

Justin Moore
  • 39
  • 1
  • 6
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Erazihel Aug 24 '17 at 15:36
  • In short you don't get to return the data. The return is happening in a different event so you don't have the data at the time you are returning. – bhspencer Aug 24 '17 at 15:37

1 Answers1

2

The first thing to do is to scour the developer doc for the library you are using to see if it offers a different interface that is designed for returning the data asynchronously (likely either via callback or promise).

If the interface you have to provide is expecting a synchronous result and is not built for an asynchronous result, then you cannot use a function that gets its result asynchronously. There's just a mismatch there and it can't be done.

The only work-around that I've sometimes seen workable is to fetch the async data ahead of time, save it locally and only initiate the other operation when you already have the data. Then you can provide a synchronous callback that will provide the data (because it's already cached locally). Obviously, whether that's feasible or not depend upon the details of the situation (often it is not feasible because the data is not known ahead of time).

The other, more drastic fix is to literally rewrite a piece of the calling library to add an async interface to it so you can return a promise and the library will use that promise appropriately. How difficult it is to convert the interface to async depends a lot on what the caller is doing and how it's built. Sometime it's straightforward and othertimes, it has a whole architecture that makes it hard to insert an async operation in the middle without substantial rewrite.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • thanks for the answer. I'm leaning towards your 'drastic' solution - patching the library I am using. Hopefully its not a rabbit hole :) – Justin Moore Aug 24 '17 at 21:07