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?

1

1 Answer 1

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);
})();
Sign up to request clarification or add additional context in comments.

3 Comments

Works fine, but still unable to use the data outside of : httpQuery(endpoint, testq) .then(list => { console.log(list) });
@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.
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.