0

From reading around and trial and error, I can't work out the best way to integrate a third-party async, callback-based function into a Promises workflow. Hoping for some pointers.

I'm building a dashboard using Google Charts and a Python-based API. I'm trying to integrate Google Spreadsheets data using Goog's Query approach:

// Create a new Query object      
var query = new google.visualization.Query('http://spreadsheets.google.com?key=123AB&...', opts);    

// Send the query with a callback function.
query.send(handleQueryResponse);

function handleQueryResponse(response) {
  // Called when the query response is returned.
  ...
}

For each chart, I'm trying to create a stack of Promises using Q.js:

// Streamlined example
Q.fcall(collectData)
.then(drawChartUsingData)
.done();

The problem is that the call to query.send() within collectData is asyncronous and so the result isn't saved to the window by the time I call drawChartUsingData. I need the next Promise in the chain to wait for the callback to finish. I'm not waiting on the return value to be passed as I'm writing that to a global variable.

Thanks in advance for any help.

PS. I'm a Python guy coming to terms with JS for the frontend, so please excuse any basic errors or lack of appreciation for JS best practice.

Phil Sheard
  • 2,102
  • 1
  • 17
  • 38
  • I don't understand how the two fragments are related. Can you create a single, simple, coherent example? – Amit Apr 13 '16 at 21:33
  • Is the first chunk of code, the one that creates `query`, in the body of `collectData`? If so, probably want to have `collectData` return a promise that gets resolved by `handleQueryResponse` http://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises – andyk Apr 13 '16 at 22:47

0 Answers0