0

I want to update a list which is defined outside of a promise (API call).

here is the code:

let data = [];
  api.getData(this.state.ID).then((resp) => {
    data = [...data, { title : resp.title }];
    data = [...data, { name :  resp.name }];
  });
  console.log(data); // --> it returns []

the data is [ ] and no value have pushed to it. how can I change my code to fix this issue? for some reasons I don't want to use setState()

Regards.

Adel
  • 3,542
  • 8
  • 30
  • 31
  • if this is exactly the order in which the code it written , it will return [ ] only, as the api.getData is async.! – semuzaboi Sep 28 '17 at 09:57
  • Ultimately, you want to render this data, correct? Heed the advice from others to solve the problem at hand, but based on how you're writing it, it can't be done without `this.setState`. I am assuming you are not using redux. – Andrew Sep 28 '17 at 10:31
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ponury-kostek Sep 28 '17 at 10:39

3 Answers3

1

Promise is ALWAYS asynchronous, meaning that your data array will still be empty after you define the promise.

To get access to filled data array you have to refer to it inside the promise.

let data = [];

api.getData(this.state.ID).then((resp) => {
    data = [...data, { title: resp.title }, { name: resp.name }];

    console.log(data);
});
euvl
  • 4,716
  • 2
  • 25
  • 30
1

Your console.log function is getting executed before api returns you data. Although data got updated after api call. You could not see it because it is consoled before that.

let data = [];
  api.getData(this.state.ID).then((resp) => {
    data = [...data, { title : resp.title }];
    data = [...data, { name :  resp.name }];
    Console.log(data)
})

Now you can see data consoles.

But if you want to console the data after then method then you can make the execution of api synchronized by using npm module q.

Prakash Sharma
  • 15,542
  • 6
  • 30
  • 37
1

Async/Await will help you:

let data = [];
async function getData() {
  await api.getData(this.state.ID).then((resp) => {
    data = [...data, { title : resp.title }];
    data = [...data, { name :  resp.name }];
  });
  console.log(data); // --> it shouldn't return empty array
}
getData();

Example:

    function resolveAfter2Seconds(x) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve("You see it after promis end");
        }, 2000);
      });
    }
    
    
    var arr = [];
    async function f1() {
      await resolveAfter2Seconds(10).then(res => arr.push(res));
      alert(arr);
    }
    f1();
Andrii Starusiev
  • 7,564
  • 2
  • 28
  • 37