【问题标题】:Return variable in Node.js [duplicate]Node.js中的返回变量[重复]
【发布时间】:2017-09-04 12:23:28
【问题描述】:

我正在尝试从 URL 收集一些 JSON 数据,并希望在整个 Node.js 应用程序中使用这些数据。在下面的代码中,JSON 被正确收集,但变量 partOfJson 返回为未定义。我猜这是因为函数 getTheData 在完成之前返回了 theData。

function getTheData() {

    const request = require('request'),url = 'myURL';

    request(url, (error, response, body)=> {
            var theData = JSON.parse(body);
    });

    //Do stuff with theData

    return theData;
};




//Somewere else
var partOfJson = getTheData();  //I want partOfJson to be parts of the collected JSON

有谁知道如何解决这个问题?我刚开始学习 Node.js,所以请放轻松。

【问题讨论】:

  • 只需在您分配“var theData=" 的位置添加返回
  • 这个问题已经被问了大约一百次了。还没来的数据是不能返回的,跟node.js也没关系。

标签: javascript node.js callback return


【解决方案1】:

是的,这是因为异步特性而发生的,您可以使用回调并在回调中返回theData,也可以使用promise 来获取值。

对于回调:

function getTheData(cb){
                 //get data from your url and store it in theData variable
                 cb(theData)
                }

你可以通过调用下面的函数来访问它:

 getTheData(function(data){
            partOfJson=data
            }

这样partOfJson 不会被定义

或者你可以走承诺的方式,这里是让你开始的链接 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

【讨论】:

    猜你喜欢
    • 2021-07-01
    • 2016-11-19
    • 2018-04-07
    • 2018-06-10
    • 2021-09-19
    • 1970-01-01
    • 2021-04-03
    • 2015-07-04
    • 1970-01-01
    相关资源
    最近更新 更多