当我收到服务器响应时如何获取这个值?
当我运行它时,终端没有输出任何信息。
console.log(a);
function findMaxID() {
var a = needle.get(URL, function(err, res){
if (err) throw err;
return 222;
});
return a;
}
最佳答案
基本上,您无法真正以函数返回值的方式返回
此值。您可以做的是为您的 findMaxID()
函数提供一个回调参数,以便在获取数据时调用:
function findMaxID(callback) {
needle.get(URL, function(err, res){
if (err) throw err;
callback(res);
});
}
然后这样调用它:
findMaxID(function(id) {
console.log('Max ID is : ', id);
}
您还可以返回一个 promise :
function findMaxID() {
return new Promise(function (resolve, reject) {
needle.get(URL, function(err, res){
if (err) reject(err);
resolve(res);
});
});
}
并这样调用它:
findMaxID().then(function(id) {
console.log('Max ID is ', id);
})
编辑
如果您使用的是 async
函数,则可以这样:
var id = await findMaxId();
console.log(id); // logs the ID
关于javascript - 如何在node.js中的get-request之后返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41806852/