Znowman
Znowman

Reputation: 395

Using data from callback outside of function

Using a function to make a http request with NodeJS. Passing a previously defined array as argument when running the function but the array is empty when console logged.

var testList = []:

var httpQuery = function(ep, q, lst) {
  ep.selectQuery(q).then(function (res) {
       return res.json()
  }).then(function (result) {
        lst = result.results.bindings;
  }).catch(function (err) {
      console.error(err)
  })
};

httpQuery(endpoint, testq, testList);

How can I get the data from the function callback in to my previously defined array and use it outside of the function?

Upvotes: 1

Views: 55

Answers (1)

TKoL
TKoL

Reputation: 13892

If you were console.logging 'testList' after calling httpQuery, then of course it would be empty. httpQuery is asyncronous, (and reassigning lst inside the fucntion wouldn't have worked anyway).

To take care of asyncronous promise-based functions, you have to return the promise and use .then()

var httpQuery = function(ep, q) {
  return ep.selectQuery(q).then(function (res) {
       return res.json()
  }).then(function (result) {
        return result.results.bindings;
  }).catch(function (err) {
      console.error(err)
  })
};

httpQuery(endpoint, testq)
    .then(list => {
        console.log(list)
    });

[edit] Depending on what version of node you're using, you may be able to use async/await. The above code is essentially equivalent to

async function httpQuery(ep, q) {
    try {
       let res = await ep.selectQuery(q);
       let result = await res.json();
       return result.results.bindings;
    } catch(e) {
       console.error(e);
    }    
}

(async () => {
    let testList = await httpQuery(endpoint, testq);
    console.log(testList);
})();

Upvotes: 2

Related Questions