-1

I'm trying to write a function that returns a series of Vote objects from the ProductHunt API on Node. I can access these objects but I don't know how to return them as the result of my function

var productHuntAPI = require('producthunt');
var productHunt = new productHuntAPI({
client_id: '123' ,// your client_id
client_secret: '123',// your client_secret
grant_type: 'client_credentials'
});

async function votesFromPage(product_id,pagenum){
    var votes;
    var params = {
    post_id:product_id,
    page:pagenum
    };

    productHunt.votes.index(params, async function (err,res) {
            var jsonres=  JSON.parse(res.body)
            votes = jsonres.votes
            console.log(votes)
    })
    return votes
}




async function main() {
    var a = await votesFromPage('115640',1)
    console.log('a is '+a)
    }
main();

Logs:
a is undefined
[Array of Vote objects]

I'd like var a to contain the votes objects so I can use it

user375348
  • 759
  • 1
  • 6
  • 23
  • 1
    You don't. Instead move the logic that depends on the result to a function that is called from within your client's callback function. – Dai Aug 02 '18 at 20:07
  • 2
    Making the callback an `async function` doesn't help. You need instead to [promisify the producthunt API](https://stackoverflow.com/q/22519784/1048572) so that you can `await` the promise then – Bergi Aug 02 '18 at 20:09
  • 1
    @Dai OP wants to use async/await, not callbacks – Bergi Aug 02 '18 at 20:09

1 Answers1

1

You need to await a promise then. So that it gets the votes and returns it.

async function votesFromPage(product_id,pagenum){

    var params = {
        post_id:product_id,
        page:pagenum
    };

    var votes = await new Promise((resolve, reject)=> {
        productHunt.votes.index(params, async function (err,res) {
            err && reject(err);
            var jsonres=  JSON.parse(res.body)
            resolve(jsonres.votes)
        });
    });
    return votes
}

EDIT: Or we have now utils.promisify does the same thing

const productHuntPromise = utils.promisify(productHunt.votes.index);
var votes = await productHuntPromise(params)
Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35