yourknightmares
yourknightmares

Reputation: 323

Saving a value through JavaScript's request method

I run into an issue when trying to use the request method in javascript where I can't save a value. I'll run a block of code like:

let savedData;

request({
  url: url,
  json: true
}, function (err, resp, body) {
  if (err) {
    return;
  }
  savedData = body.data;
});

console.log(savedData);

I know that request doesn't block or something, so I think it's run after the console.log or something like that? I just need to know how I can save the desired data for use later in the method.

Upvotes: 1

Views: 837

Answers (2)

Trent
Trent

Reputation: 4306

Your code is working correctly, you're just neglecting the fact that the callback provided as a second parameter to request() is executed asynchronously.

At the time when your console.log() is executed, the network request may or may not have successfully returned the value yet.


Further Explanation

Take a look at the documentation for the request() function.

It states that the function call takes the following signature,

request(options, callback); 

In JavaScript, a callback performs exactly as the name perscribes; it calls back by executing the provided function, after it has done what it first needs to.

This asynchronous behavior is especially prominent in making networking requests, since you wouldn't want your program to freeze and wait for the network request to retrieve or send what you've requested.


Example

function callback() {
   console.log('I finished doing my asynchronous stuff!');
   console.log('Just calling you back as I promised.'); 
}

console.log('Running some asynchronous code!');
request({...options}, callback);

console.log('Hi! I'm being called since I'm the next line of code; and the callback will be called when its ready.');

Output

  • Running some asynchronous code!
  • Hi! I'm being called since I'm the next line of code; and the callback will be called when its ready.
  • I finished doing my asynchronous stuff!
  • Just calling you back as I promised.

Upvotes: 4

Dan Oswalt
Dan Oswalt

Reputation: 2189

You'll either need to do the rest of the code in the callback of the request function, or use a promise. Anything outside of that callback is going to execute before saveedData ever shows up.

Upvotes: 2

Related Questions