Node.js承诺请求返回

Sam*_*m H 6 request node.js promise

我正在使用promis模块从请求模块返回我的json数据,但每次运行它时,它都会给我这个.

Promise { _45: 0, _81: 0, _65: null, _54: null }
Run Code Online (Sandbox Code Playgroud)

我无法让它工作,任何人都知道这个问题?这是我的代码:

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());
Run Code Online (Sandbox Code Playgroud)

jfr*_*d00 20

承诺是一个对象,作为未来价值的占位符.您的parse()函数返回该promise对象.您可以通过将.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);
});
Run Code Online (Sandbox Code Playgroud)

这是异步代码,因此您从承诺中获取值的唯一方法是通过.then()处理程序.

修改清单:

  1. .then()在返回的promise对象上添加处理程序以获得最终结果.
  2. .catch()在返回的promise对象上添加处理程序以处理错误.
  3. errrequest()回调中添加错误检查值.
  4. 添加try/catch,JSON.parse()因为它可以抛出无效的JSON


Ode*_*ner 8

使用请求承诺

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

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