-1

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 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?

Thank you

Pedro Guerra
  • 21
  • 2
  • 5
  • why don't you move the if else block inside the request callback ? it is showing you default value because the promise takes time to resolve while your other code executes before. – anees Mar 31 '20 at 20:32
  • all the code outside `then` after it, ie the if and res.render fires before the request is resolved, just plop it all inside the `then`.. `then` work on refactoring out `request` lib its deprecated. – Lawrence Cherone Mar 31 '20 at 20:36
  • Firstly explain ur question properly then put -1 on my answers – Mark Minerov Mar 31 '20 at 21:06

3 Answers3

2

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

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");
});
anees
  • 1,777
  • 3
  • 17
  • 26
0

Using await in an async functions allows you to use a more imperative programming style, as it waits for the promise to be resolved (blocking):

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

You might want to add manual error handling via try-catch around that.

Matt
  • 116
  • 6
  • 3
    Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality and are more likely to attract upvotes. – Suraj Kumar Apr 01 '20 at 05:56
  • Please add a few sentences to explain what your code is doing, so you can get more upvotes for your answer. – Fuzzy Analysis Apr 01 '20 at 07:22
-1

Try this:

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");
});
Mark Minerov
  • 309
  • 1
  • 8