0

Consider the following code, take from this example: How is an HTTP POST request made in node.js?

var request = require('request');

request.post(
    'http://www.yoursite.com/formpage',
    { json: { key: 'value' } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body);
        }
    }
);

How do I make the variable body known globally in the program and not only in the anonymous function?

The problem I face is that my function is surrounded by a function which has to return the value of what is queried in the request of the url.

David
  • 2,926
  • 1
  • 27
  • 61
  • 1
    The function is **asynchronous** so making the variable global won't really do you any good. What you need to do is place the "work" necessary *inside* the callback function. – Pointy Jul 23 '19 at 01:44
  • Is it not possible to wait until it is finished and then make it known globally or it is the wrong way to do this in javascript? – David Jul 23 '19 at 01:46
  • 1
    Generally there's no "waiting" in JavaScript. There are facilities to make code *appear* to wait — `async` functions and the `await` expression — but those work with Promise objects and everything is still asynchronous. – Pointy Jul 23 '19 at 11:49

0 Answers0