How to use await to get JSON response and retry if it's returned NULL

Viewed 22

My app has a search function that returns JSON.

The JSON will return NULL if it's not -quite- ready and needs a few more seconds to process.

If the JSON request is returned as NULL, I need to retry every second until it's not NULL.

Here is my JS:

async search(q, callback) {
  const response = await get(this.urlValue, {
    query: { q: q },
    responseKind: 'json'
  })

  if (response.ok) {
    const list = await checkIfResponseNotNull();
  }

  function checkIfResponseNotNull() {
    return new Promise(resolve => {
      setTimeout(() => {
        if (response.json === null) {
          // Try again?
        } else {
          return callback(response.json)
        }
      }, 500)
    })
  }

}
1 Answers

You could recursively call the search method when response, or response.json, is null.

const search = async (q, callback) => {
  console.log("searching for: " + q);
  try {
    const response = await get();

    console.log(response);
    if (response?.json) {
      console.log("response found");
      return callback(response.json);
    }

    console.log("retry search");
    await search(q, callback);
  } catch {
    // await search(q, callback) // Also try again when request fauls?
  }
};

A simple example can be found here: here

Related