请求-等待API调用完成Node.js [英] Request - Wait till API call is completed Node.js

查看:68
本文介绍了请求-等待API调用完成Node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在回调函数方面遇到问题,但找不到解决方案.我需要在回调中获取一个值以进行最近比较.问题是,当我比较时,我的变量仍然具有初始值.

I'm facing a problem with callback functions and I can't find a solution for that. I need to get one value inside a callback to compare lately. The problem is, when I compare, my variable is still with initial value.

router.get('/qadashboard', (req, res) => {
    var total = -1;

    var options = {
        method: 'GET',
        uri: 'https://myurl.com/users',
        json: true
    };

    request(options)
    .then((response) => {
        // Get Total
        total = response.body.total;
    })
    .catch((err) => {
        console.log('API Error - ', err);
    });

    if (total < 10) {
        // Code here
    } else {
        // Code here
    }

    res.render("index");
});

Total始终为-1,并且我确定response.body.total并非为-1(始终返回正数).如果我在回调函数中编写console.log(response.body.total),它将返回正确的数字.有什么方法可以等到回调执行完成之后再进行比较,如果total<10?

Total is always -1 and I am sure that response.body.total is not -1 (always return positive numbers). If I code console.log(response.body.total) inside the callback function it's returning the right number. Is there any way that I can wait till callback execution is finish and later on compare if total < 10?

谢谢

推荐答案

好的,所以第一个解决方案是将条件和响应块移动到promise中.

ok so first solution would be to move the condition and response block inside the promise.

router.get('/qadashboard', (req, res) => {
    var total = -1;

    var options = {
        method: 'GET',
        uri: 'https://myurl.com/users',
        json: true
    };

    request(options)
    .then((response) => {
        // Get Total
        total = response.body.total;
        if (total < 10) {
            // Code here
        } else {
            // Code here
        }

        res.render("index");
    })
    .catch((err) => {
        console.log('API Error - ', err);
        res.render("error"); // maybe render an error view
    });
});

或者您也可以等待使用async/await

or you can also wait for the promise to resolve using async/await

router.get('/qadashboard', async (req, res) => {
    var total = -1;

    var options = {
        method: 'GET',
        uri: 'https://myurl.com/users',
        json: true
    };

    try{
        let resp = await request(options);
        total = resp.body.total;
    }catch(err){
        console.log('API Error - ', err);
    }

    if (total < 10) {
        // Code here
    } else {
        // Code here
    }

    res.render("index");
});

这篇关于请求-等待API调用完成Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆