0

I'm writing app in node.js and using npm request package.

I need to save value from function getData() into variable num.

const getData = () => {
    request({url: 'url.com', json: true}, (error, response) => {
        response.body.numbers;    
    });
    return // somehow to return value
}

const num = getData();

I cannot figure out how to return value/response from request function. Variable num cannot be inside any function. Any ideas?

Rodny
  • 25
  • 2
  • I'd suggest you first stop using the `request()` library because it has been deprecated and should probably not be used for new projects. I'd suggest the `got()` library instead, but there are plenty of alternatives to look at [here](https://github.com/request/request/issues/3143). – jfriend00 Jun 10 '20 at 01:16
  • Then, I'd suggest you use promises, not plain callbacks. – jfriend00 Jun 10 '20 at 01:16
  • I used Promises and Callbacks, but it did not work for me because I cannot put the variable inside any functions - the code must be `const num = getData();` – Rodny Jun 10 '20 at 01:25
  • Your code does not have to be `const num = getData()`. If you really require that, then you need a different programming environment because node.js does not do that. But, chances are 99.9999999% that something else can be rewritten to work with an asynchronous response from a promise. You just need to learn how to do that. For example if `getData()` returns a promise that resolves to the final value, then you can do `const num = await getData();`. But, the code that uses `num` can also be put inside a `.then()` handler from the promise with a little code reorganization. – jfriend00 Jun 10 '20 at 01:51

0 Answers0