我是NodeJS的新手,我试图创建一个函数并返回一个值,但是当我将其调用时返回“未定义”时,这是我的代码,希望大家能为我提供帮助。
function getData (jsonData){
var json;
request(jsonData, function(error, response, body){
if(body){
json = JSON.parse(body);
}else{
json = error;
}
});
return json;
}
答案 0 :(得分:-1)
由于请求函数是异步操作,因此即使在调用请求的回调之前,函数也会返回,因此可以使用以下方法。
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。承诺方法:承诺是一种处理异步功能的好方法。将您的功能包装在一个承诺中。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
// 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
getData({})
.then(response => console.log(response))
.error(error => console.log(error));
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);
}