R
R
rockwell3232020-06-28 18:41:40
JavaScript
rockwell323, 2020-06-28 18:41:40

How to pass the result of a request request to an external variable?

let a = '';  //переменная куда я хочу поместить результат запроса request(option, myFunction), что бы в дальнейшем ее использовать в коде;

const option = {
  url: 'example.com',
  method: 'GET'
};

function myFunction(e, r, body){
  let jsonParse = JSON.parse(body);  //приходит обьект, откуда я в дальнейшем получаю 1 значение;
  a += jsonParse;  //пытаюсь полученное значение записать во внешнюю переменную
};

request(option, myFunction);

console.log(a) //в итоге получаю пустую строку без переменной из запроса выше

How can I solve this issue?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FinGanapre, 2020-06-28
@rockwell323

You have asynchronous code. At the time of calling the output to the console, the value in the variable a has not yet been assigned. Use promise or async/await.
For convenience, use axios.
To better understand the situation, add output to the console in the body of myFunction. It will be seen that your current output to the console will be executed first, and only then in the body of the myFunction function

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question