Async request problem with variables

Asked

Viewed 45 times

1

The problem is with variables why the function async is running after the variable assignment. what can I do for the function to run and wait for it to finish to take the variable value?

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

1 answer

0


Directly, the way it is, you can’t use foo out of 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 string . then():

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

One way or another, you never escape the fact that you are postponing the moment to display the information() result from the console.log().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.