0

When I try to call this oauth-1.0 API request,

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;

it returns

Promise { < pending > }

undefined

However when I just use console.log(body), it gives the correct result

..................

.................

....

.....

.....

.....

Community
  • 1
  • 1
John C
  • 517
  • 2
  • 6
  • 16
  • You have to wait for the promise to resolve in the `.then` callback. – nem035 Jul 12 '18 at 11:12
  • Check it out: https://stackoverflow.com/questions/28921127/how-to-wait-for-a-javascript-promise-to-resolve-before-resuming-function – vahdet Jul 12 '18 at 11:12
  • I was following the layout for the IBM Cloud Functions Weather Template, which has almost the exact same layout as mine (except mine is oauth and the weather isn't). I'm just not sure why that one works but mine does not – John C Jul 12 '18 at 11:40

1 Answers1

1

Actually it it works correct and returns Promise.

So if you want to get "data" from promise, you should use Promise.then()

Like in this example from MDN.

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

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

Hope it helps!

noctifer20
  • 188
  • 6