1

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?

Znowman
  • 385
  • 1
  • 5
  • 19
  • 1
    Possible duplicate of [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Mikey Feb 28 '18 at 19:50

1 Answers1

2

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);
})();
TKoL
  • 13,158
  • 3
  • 39
  • 73
  • Works fine, but still unable to use the data outside of : httpQuery(endpoint, testq) .then(list => { console.log(list) }); – Znowman Feb 28 '18 at 20:14
  • @Znowman if I think I understand what you mean by 'outside of', then you will *never* be able to get it to work 'outside' of that, because these are asyncronous calls. You will only ever be able to get access to the result of httpQuery inside of a `.then` or `await` following the call of the httpQuery function. What you're asking for is impossible. – TKoL Mar 01 '18 at 08:58
  • @Znowman and more importantly, you're mistaken for thinking you have any reason to *need* to access it the way you think you do. Whatever logic you have that uses the result of httpQuery *can be run just fine* after awaiting the result, or running it inside of a `.then` – TKoL Mar 01 '18 at 09:00