0

In my simplified code:

static getData(Id) {
  const data = [];
  api.getData(lId)
    .then((Res) => {
      data.push(Res);
    });
  return data;
}

The API endpoint gets the data but it takes some time. the method always returns [], but if I put a console.log(Res), the data is there. It means the method returns the initial const data = []; and it doesn't wait until the API returns the data.

How should I fix this problem?

Regrds

Adel
  • 3,542
  • 8
  • 30
  • 31

2 Answers2

1

You should use Promise.

For example:

static getData(Id) {
  return new Promise((resolve) => {
    api.getData(Id)
      .then((Res) => {
         resolve(Res);
      });
  });
}

And use this method like this:

getData(15)
  .then((data) => {
    console.log(data);
  });
Kenji Mukai
  • 599
  • 4
  • 8
1

There's a problem with your timing here:

static getData(Id) {
  const data = [];
  api.getData(lId)
    .then((Res) => {
      data.push(Res);
    });
  return data;  <-- Gets returned before the promise resolves/rejects
}

If you need to do extra processing on your data before it is returned to the caller - in your example, you're putting it into an array - you're going to need to wrap it with another Promise:

static getData(Id) {
  return new Promise((resolve, reject) => {
      api
        .getData(Id)
        .then((Res) => {
          const data = []
          data.push(Res);
          resolve(data)
        })
        .catch(reject)
  })
}
lux
  • 8,315
  • 7
  • 36
  • 49