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 resolve() method: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.
fetch() The global fetch() method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the Response object representing the response to your request.
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);
});
This is asynchronous code so the ONLY way you get the value out of the promise is via the .then()
handler.
List of modifications:
.then()
handler on returned promise object to get final result..catch()
handler on returned promise object to handle errors.err
value in request()
callback.JSON.parse()
since it can throw if invalid JSONUse request-promise:
var rp = require('request-promise');
rp('http://www.google.com')
.then(function (response) {
// resolved
})
.catch(function (err) {
// rejected
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With