I
I
Igor Myasnikov2018-01-31 14:13:07
JavaScript
Igor Myasnikov, 2018-01-31 14:13:07

How to return data received with fetch?

Good day.
There is a Fetch request:

let data = fetch('some url')
  .then(
    response => response,
    error => alert(`Rejected: ${error}`)
  );

How can I put the request body (json) in the data variable and use it already in another file?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
OKyJIucT, 2018-01-31
@pilium

var data = null;
fetch('some url')
  .then(
    response => {
        data = response;
    },
    error => alert(`Rejected: ${error}`)
  );

But the data will be in the data variable only after the request is completed. Maybe it makes sense to call a function and pass data as a parameter to it, for example, like this:
fetch('some url')
  .then(
    response => {
        someFunc(response);
    },
    error => alert(`Rejected: ${error}`)
  );

someFunc(data) {
    alert(data);
}

Then it will be executed upon completion of the request, and there will be no need to check data for the presence of data in it. That is, the actions will be performed sequentially.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question