【问题标题】:Request - Wait till API call is completed Node.js请求 - 等待 API 调用完成 Node.js
【发布时间】:2020-07-12 12:34:06
【问题描述】:

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

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) 代码,它会返回正确的数字。 有什么方法可以等到回调执行完成,然后再比较是否总计

谢谢

【问题讨论】:

  • 为什么不在请求回调中移动 if else 块?它向您显示默认值,因为在您之前执行其他代码时,promise 需要时间来解决。
  • then 之后的所有代码,即 if 和 res.render 在请求解决之前触发,只需将其全部放入 then.. then 进行重构request lib 已弃用。
  • 首先正确解释你的问题,然后在我的答案上加上-1

标签: javascript node.js express request-promise


【解决方案1】:

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

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 等待 promise 解决

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");
});

【讨论】:

  • Anees,由于其他原因,我无法移动条件,但 async/await 工作正常。非常感谢
【解决方案2】:

在异步函数中使用await 允许您使用更命令式的编程风格,因为它等待承诺被解决(阻塞):

const response = await request(options);   // wait for response
total = response.body.total;
..

您可能希望通过 try-catch 添加手动错误处理。

【讨论】:

  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常质量更高,更有可能吸引投票。
  • 请添加几句话来解释您的代码在做什么,以便您的回答获得更多的支持。
【解决方案3】:

试试这个:

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
        }
    })
    .catch((err) => {
        console.log('API Error - ', err);
    });

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 2016-02-17
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多