Node.JS - Return 承诺给予 'undefined'

Node.JS - Return Promise Gives 'undefined'

当我尝试调用此 oauth-1.0 API 请求时,

const request = require('request');
const OAuth = require('oauth-1.0a');
const crypto = require('crypto');

function main(params) {
    // Dependencies
    // Initialize
    const oauth = OAuth({
        consumer: {
            key: '****',
            secret: '****'
        },
        signature_method: 'HMAC-SHA1',
        hash_function(base_string, key) {
            return crypto.createHmac('sha1', key).update(base_string).digest('base64');
        }
    });
    // Note: The token is optional for some requests
    const token = {
        key: '****',
        secret: '****'
    };

    const request_data = {
        url: 'http://****/rest/V1/products/12345',
        method: 'GET',
        //data: { status: 'Hello Ladies + Gentlemen, a signed OAuth request!' }
    };

    return new Promise((resolve, reject) => {
        request({
            url: request_data.url,
            method: request_data.method,
            form: request_data.data,
            headers: oauth.toHeader(oauth.authorize(request_data, token))
        }, function (err, res, body) {
            //console.log(res.body.name);
            if (err){ 
                reject({
                    statusCode: 500,
                    headers: { 'Content-Type': 'application/json' },
                    body: {'message': 'Error processing your request' },
                  });    
            } else {
                resolve({
                    body: JSON.parse(body),
                })
            }
        });
    });
};
exports.main = main;

它returns

Promise { < pending > }

undefined

然而,当我只使用 console.log(body) 时,它给出了正确的结果

.......

.......

.....

.....

.....

.....

实际上它工作正常 returns 承诺。

所以如果你想从 promise 中得到 "data",你应该使用 Promise.then()

就像来自 MDN 的这个例子。

const promise1 = new Promise(function(resolve, reject) {
  resolve('Success!');
});

promise1.then(function(value) {
  console.log(value);
  // expected output: "Success!"
});

希望对您有所帮助!