Node.js 承诺请求返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41412512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js promise request return
提问by Sam H
I'm using the promis module to return my json data from the request module, but every time i run it, it gives me this.
我正在使用 promis 模块从请求模块返回我的 json 数据,但是每次我运行它时,它都会给我这个。
Promise { _45: 0, _81: 0, _65: null, _54: null }
I can't get it to work, any one know the problem? here is my code:
我无法让它工作,有人知道问题吗?这是我的代码:
function parse(){
return new Promise(function(json){
request('https://bitskins.com/api/v1/get_account_balance/?api_key='+api+'&code='+code, function (error, response, body) {
json(JSON.parse(body).data.available_balance);
});
});
}
console.log(parse());
回答by jfriend00
A promise is an object that serves as a placeholder for a future value. Your parse()function returns that promise object. You get the future value in that promise by attaching a .then()handler to the promise like this:
承诺是一个对象,用作未来值的占位符。您的parse()函数返回该承诺对象。通过将.then()处理程序附加到承诺中,您可以获得该承诺中的未来值,如下所示:
function parse(){
return new Promise(function(resolve, reject){
request('https://bitskins.com/api/v1/get_account_balance/?api_key='+api+'&code='+code, function (error, response, body) {
// in addition to parsing the value, deal with possible errors
if (err) return reject(err);
try {
// JSON.parse() can throw an exception if not valid JSON
resolve(JSON.parse(body).data.available_balance);
} catch(e) {
reject(e);
}
});
});
}
parse().then(function(val) {
console.log(val);
}).catch(function(err) {
console.err(err);
});
This is asynchronous code so the ONLY way you get the value out of the promise is via the .then()handler.
这是异步代码,因此您从承诺中获取值的唯一方法是通过.then()处理程序。
List of modifications:
改装清单:
- Add
.then()handler on returned promise object to get final result. - Add
.catch()handler on returned promise object to handle errors. - Add error checking on
errvalue inrequest()callback. - Add try/catch around
JSON.parse()since it can throw if invalid JSON
.then()在返回的承诺对象上添加处理程序以获得最终结果。.catch()在返回的 promise 对象上添加处理程序以处理错误。err在request()回调中添加对值的错误检查。- 添加 try/catch around,
JSON.parse()因为如果 JSON 无效,它会抛出
回答by Oded Breiner
Use request-promise:
使用请求承诺:
var rp = require('request-promise');
rp('http://www.google.com')
.then(function (response) {
// resolved
})
.catch(function (err) {
// rejected
});

