Node.js - Asynchronous JSON Query

2019-03-04 05:29发布

I apologize if this is a stupid question, but I am new to Javascript and Node.js really hurts my head because it is asynchronous.

My goal is to query for a JSON object from an API and be able to work with it. I have tried to look for questions and answers on what I should be doing but none of it really makes sense to me, so I am hoping to learn by just seeing proper code.

var request = require('request');

var url = 'url here';
var temp;
var done = false;

request(url, function (error, response, body) {
    if (!error) {
      temp = body;
      done = true;
      console.log(temp);
    } else {
        console.log(error);
    }
});

if (done){
  console.log(temp);

}

Can someone please walk me through the proper way to restructure my code?

1条回答
贪生不怕死
2楼-- · 2019-03-04 06:29

The function you are creating with the line

request(url, function (error, response, body) {

is not executed until the response is received. The rest of your code continues to run. Think of the flow something like this:

var request = require('request');

var url = 'url here';
var temp;
var done = false;

request(url, XXX);

if (done){
  console.log(temp);

then when the response is received (perhaps much later on) the function XXX is executed.

As you can see, done will always be false when the line

if (done){

is executed.

查看更多
登录 后发表回答