1

I'm trying to get the PromiseValue in the renderSelect. (in tmp)

The thing is that I'm getting a promise, which is the normal behavior. But I don't understand how could I get the values inside the Promise so I can work with them.

I have an ApiService class as follows

handleResponse(response) {
  if (response.status >= 200 && response.status < 300) {
    return response.json();
  }
  return response.json()
    .then((res) => {
      throw new Error(res.message);
    },
    () => {
      throw new Error();
    });
}


get(url) {
  return fetch(`${this.API_URL}${url}`, {
    method: 'GET',
    headers: this.headers,
  })
    .then(response => this.handleResponse(response));
}

And my .jsx like this

const getOptions = (contractor_employee_id) => {
  const apiService = new ApiService()
  return apiService
    .get(`some_url`)
    .then(
      response => {
        return ["toto", "tata", "titi"]
    },
    err => (console.log("Failed"))
    );
};

const renderSelect = (field) => {
  const tmp = getOptions(field.id)
  console.log(tmp)
Difender
  • 495
  • 2
  • 5
  • 18

2 Answers2

2

Promises are asynchronous. And if you want to return promise result in synchronous way, use async / await.

const renderSelect = async (field) => {
    const tmp = await getOptions(field.id)
    console.log(tmp)
}
Ankit Parikh
  • 116
  • 1
  • 3
0

You can use Javascript Promise to return a promise to renderSelect

const getOptions = (contractor_employee_id) => {
  const apiService = new ApiService()
  return new Promise((resolve, reject) => {
        apiService
            .get(`some_url`)
            .then(
              response => {
                resolve(["toto", "tata", "titi"]);
            },
            err => (console.log("Failed") reject('failed');)
            );
        };

       })
}

const renderSelect = (field) => {
  getOptions(field.id).then((res) => {
      console.log(tmp);
  })
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400