Async request problem with variables

1

The problem is with variables why the async function is executing after variable assignment. what can I do for the execute function and wait for it to finish to get the value of the variable?

var request = require('request');
function information(callback) {
    var options = {
        url: "http://someurl.com",
        method: "GET",
        headers: {
            Token: "MV"
        }
    }
    request(options, function (error, response, body) {
        if (!error) {
            try {
                json = JSON.parse(body);
                callback(json);
            } catch (error) {
                error = 'error'
                callback(error);
            }

        }
    })
}
var foo;
information(function (bar) {
        if (bar) {
            console.log(foo);
            foo = bar;
            console.log(foo);
        }
    }) 
console.log(foo);
    
asked by anonymous 26.03.2018 / 20:26

1 answer

0

Directly, as it stands, you can not use foo outside the callback passed by information (). There are two ways to make the main asynchronous code more readable. One is to turn your original method into a Promise and use the .then () string:

function information_p()
{
    return new Promise(function (ok, nok) {
        information(function (resp) {
            ok(resp);
        });
    });
}

information_p().then(console.log);

A Promise can be used with the await keyword instead of .then (), but await can only be used within an async function, which creates an "egg or chicken" problem to make the first await. One way is to create an anonymous async function and invoke it:

(async function () {
    var foo = await information_p();
    console.log(foo);
})();

In one way or another, you never escape the fact that you are putting off the momentum of displaying information () through console.log ().

    
27.03.2018 / 06:41