Node.js Promise请求返回

10
我正在使用promise模块从请求模块返回我的json数据,但每次运行它时,它都会给我这个。
Promise { _45: 0, _81: 0, _65: null, _54: null }

我无法让它工作,有人知道问题所在吗?这是我的代码:

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());

承诺会返回一个承诺,即在稍后的某个时间点解决(.then)或拒绝(.catch)一些数据的合同。我建议你仔细阅读它们。您正在记录返回的承诺。此时,您的请求尚未返回。 - ste2425
3个回答

38

Promise是一个用于代表未来的值的对象。你的parse()函数会返回该Promise对象。通过将.then()处理程序附加到Promise,您可以获得该Promise中的未来值,例如:

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);
});

这是异步代码,所以你唯一可以通过.then()处理程序获取promise的值。

修改列表:

  1. 在返回的 promise 对象上添加 .then() 处理程序来获取最终结果。
  2. 在返回的 promise 对象上添加 .catch() 处理程序来处理错误。
  3. request() 回调中添加对 err 值的错误检查。
  4. JSON.parse() 周围添加 try/catch 语句,因为它可能会在无效的 JSON 上抛出异常。

8
请使用request-promise
var rp = require('request-promise');

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

0
// https://www.npmjs.com/package/request
const request = require('request')

/* --- */

/* 
    "Producing Code" (May take some time) 
 */
let myPromise = new Promise( function( resolve, reject ) {

    request( 'https://example.com', function ( error, response, body ) {

        if ( error ) return reject( error )
        
        try {

            resolve( body )
            
        } catch ( error ) {
            
            reject( error )
            
        }
        
    } )
    
} )

/* --- */

/* 
    "Consuming Code" (Must wait for a fulfilled Promise) 
 */
myPromise.then(
    
    function( success ) { 
        
        /* code if successful */ 
        console.log( success )
        
    },
    
    function( error ) { 
        
        /* code if some error */ 
        console.error( error )
        
    }
    
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接