问题描述
我正在使用 promis 模块从请求模块返回我的 json 数据,但每次运行它时,它都会给我这个.
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.
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());
推荐答案
promise 是一个对象,用作未来值的占位符.您的 parse()
函数返回该承诺对象.您可以通过将 .then()
处理程序附加到承诺中来获得该承诺中的未来值,如下所示:
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:
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);
});
这是异步代码,因此您从 promise 中获取值的唯一方法是通过 .then()
处理程序.
This is asynchronous code so the ONLY way you get the value out of the promise is via the .then()
handler.
修改列表:
- 在返回的 promise 对象上添加
.then()
处理程序以获得最终结果. - 在返回的 promise 对象上添加
.catch()
处理程序以处理错误. - 对
request()
回调中的err
值添加错误检查. - 在
JSON.parse()
周围添加 try/catch,因为如果 JSON 无效,它会抛出
- 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
err
value inrequest()
callback. - Add try/catch around
JSON.parse()
since it can throw if invalid JSON
这篇关于Node.js 承诺请求返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!