Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js NodeJS中未定义的返回变量_Node.js - Fatal编程技术网

Node.js NodeJS中未定义的返回变量

Node.js NodeJS中未定义的返回变量,node.js,Node.js,我是NodeJS的新手,我试图创建一个函数并返回一个值,但当我称它为return“UNDEFINED”时,这是我的代码,希望你们能帮助我 function getData (jsonData){ var json; request(jsonData, function(error, response, body){ if(body){ json = JSON.parse(body); }else{ json = error;

我是NodeJS的新手,我试图创建一个函数并返回一个值,但当我称它为return“UNDEFINED”时,这是我的代码,希望你们能帮助我

function getData (jsonData){
   var json;
   request(jsonData, function(error, response, body){
     if(body){
       json = JSON.parse(body);
     }else{
       json = error;
     }
   });

   return json;
}

由于您的请求函数是异步操作,所以即使在调用请求回调之前,您的函数也会返回,您可以使用以下方法

1。回调方法:使getData函数成为回调函数,并在主体中得到响应后调用回调函数

// Definition
function getData (jsonData, cb){
   request(jsonData, function(error, response, body){
     if(body){
       return cb(null, JSON.parse(body));
     }
     return cb(error);
   });
}

// Invocation
getData({}, function(error, response) {
  if (error){
    console.log(error);
    return;
  }
  console.log(response);
})
2。Promises方法:Promises是处理异步函数的好方法。将您的函数包装在承诺中

3。异步等待方法:这是以同步方式编写异步函数的新方法。对于这一点,定义上没有任何变化,比如在请求使用回调时承诺

// Definition
function getData (jsonData){
  return new Promise((resolve, reject) => {
    request(jsonData, function(error, response, body){
      if(body){
        return resolve(JSON.parse(body));
      }
      return reject(error);
   });
  });
}

// Invocation if calling outside
(async() => {
  try {
    const response = await getJsonData({});
    console.log(response); 
  } catch (err) {
    console.log(err);
  }
})();

// in another function
async function test() {
  const response = await getJsonData({});
  console.log(response);
} 


我相信你的身体在你的
响应
中,而不是请求回调的第三个参数。我使用的第三种方法对我来说是最好的,但它向我显示了这个错误“SyntaxError:await仅在异步函数中有效”@AlexAguilarMurillo更新了我的答案,如果在另一个函数中使用
getJsonData
,则必须将该函数标记为异步。
// Definition
function getData (jsonData){
  return new Promise((resolve, reject) => {
    request(jsonData, function(error, response, body){
      if(body){
        return resolve(JSON.parse(body));
      }
      return reject(error);
   });
  });
}

// Invocation if calling outside
(async() => {
  try {
    const response = await getJsonData({});
    console.log(response); 
  } catch (err) {
    console.log(err);
  }
})();

// in another function
async function test() {
  const response = await getJsonData({});
  console.log(response);
}