Але*_*зев 1 javascript node.js needle.js
当我收到服务器响应时如何获取这个值?
当我运行它时,终端没有输出任何信息。
console.log(a);
function findMaxID() {
var a = needle.get(URL, function(err, res){
if (err) throw err;
return 222;
});
return a;
}Run Code Online (Sandbox Code Playgroud)
基本上,您无法以return函数返回值的方式真正获得该值。您可以做的是为您的findMaxID()函数提供一个回调参数,以便在获取数据时调用:
function findMaxID(callback) {
needle.get(URL, function(err, res){
if (err) throw err;
callback(res);
});
}
Run Code Online (Sandbox Code Playgroud)
然后这样称呼它:
findMaxID(function(id) {
console.log('Max ID is : ', id);
}
Run Code Online (Sandbox Code Playgroud)
您还可以返回一个承诺:
function findMaxID() {
return new Promise(function (resolve, reject) {
needle.get(URL, function(err, res){
if (err) reject(err);
resolve(res);
});
});
}
Run Code Online (Sandbox Code Playgroud)
并这样称呼它:
findMaxID().then(function(id) {
console.log('Max ID is ', id);
})
Run Code Online (Sandbox Code Playgroud)
或者像这样如果你在一个async函数下:
var id = await findMaxId();
console.log(id); // logs the ID
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6805 次 |
| 最近记录: |