Node.js的 - 异步JSON查询 [英] Node.js - Asynchronous JSON Query

查看:199
本文介绍了Node.js的 - 异步JSON查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我道歉,如果这是一个愚蠢的问题,但我是新来的Javascript和Node.js的真心疼我的头,因为它是异步的。

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.

我的目标是查询从API JSON对象,并能与它合作。我试图寻找什么我应该做但没有真的对我来说很有意义的问题和答案,所以我希望通过只看到适当的code学习。

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);

}

有人请我走通过适当的方式调整自己的code?

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

推荐答案

您正在创建与线下功能

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

不执行,直到接收到响应。您code的其余部分继续运行。想想流程是这样的:

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);

那么当接收到响应(也许是很久以后的)函数执行 XXX

正如你所看到的,完成将永远是假的时行

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

if (done){

执行

这篇关于Node.js的 - 异步JSON查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆