如何在回调后将值返回给main函数

问题描述 投票:-1回答:1

我正在尝试编写一个函数,该函数从Node上的ProductHunt API返回一系列Vote对象。我可以访问这些对象,但我不知道如何返回它们作为我的函数的结果

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

日志: a未定义 [投票对象数组]

我想var a包含投票对象,所以我可以使用它

javascript node.js async-await
1个回答
1
投票

你需要await承诺。这样它就可以获得投票并返回。

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
}

编辑:或者我们现在有utils.promisify做同样的事情

const productHuntPromise = utils.promisify(productHunt.votes.index);
var votes = await productHuntPromise(params)
© www.soinside.com 2019 - 2024. All rights reserved.