Node.js promise request return

Use request-promise:

var rp = require('request-promise');

rp('http://www.google.com')
    .then(function (response) {
        // resolved
    })
    .catch(function (err) {
        // rejected
    });

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:

  1. Add .then() handler on returned promise object to get final result.
  2. Add .catch() handler on returned promise object to handle errors.
  3. Add error checking on err value in request() callback.
  4. Add try/catch around JSON.parse() since it can throw if invalid JSON