0

I have a function outside my control which triggers a series of callbacks to a function I control, and upon receiving an end message, I want to trigger some followup actions.

function myFunction(data)
{
  if(!!data)
  {
    global.finished = true;
  }
  else
  {
    global.loadedData += data;
  }
}

function getInfoAboutData()
{
  EXTERNAL.getData(myFunction); // returns immediately, then async calls myFunction until done, then calls with null

  // PROBLEM -> Wait on data to be loaded, or return something I can wait on

  return data.substring(...)
}

I'm open to returning a promise I can wait on in the calling function, or if there's a way to wait on global.finished === true.

Edit: To clarify, I'm looking for advice on how I wrap the loadedData flag in a promise here, since getData does not return a promise, and does not wait on completion to return.

MHill
  • 29
  • 2
  • 8
  • Either a Promise or pass a callback is the way to follow (perhaps with a Promise the workflow will be much clean). – MarcoL Mar 15 '16 at 16:38
  • 1
    Whatever you do, `getInfoAboutData` cannot return the data. You cannot "wait" for an asynchronous function. – Felix Kling Mar 15 '16 at 16:38
  • How do I wrap a check on global.loadedData in a promise here? EXTERNAL.getData() does not return a promise, and does not wait for the result to complete. – MHill Mar 15 '16 at 16:45
  • `getInfoAboutData ` will have to return the promise. `function getInfoAboutData() { return new Promise(function(resolve, reject) { EXTERNAL.getData(resolve); });` or similar. – Felix Kling Mar 15 '16 at 16:51
  • Can I resolve within myFunction here? if(!!data) { resolve() } – MHill Mar 15 '16 at 16:52
  • The idea would be to move the logic of my `myFunction` into the callback you pass to `Promise`. But there wouldn't be a need for setting global variables if you have promise, so I'm not sure what purpose `myFunction` would serve at this point. – Felix Kling Mar 15 '16 at 18:35

0 Answers0