whydoifly
whydoifly

Reputation: 67

Convert Promise to Async Await

I am converting different code snippets with promise functions into async await functions. VS Code can do it automatically, but in some places I have to do it manually as VS Code doesn't highlight the promise syntax. Could anybody show me one example of converting promise to async based on this expression?

const getJson = url => fetch(url).then(res => res.json());

    getJson('/i/1.json')
    .then(json => {
        if (json.key) {
            return getJson('/i/2.json')
        }
        throw new Error('No key')
    })
    .then(json => {
        return json.key2
    })
    .catch(error => {
        console.error(error)
    })

Following this article https://advancedweb.hu/how-to-refactor-a-promise-chain-to-async-functions/ I guess I should get something like this:

const getJson = url => fetch(url).then(res => res.json());

const getJson1 = await getJson();
const getJson2 = await getJson2(key);
const getJson3 = await getJson3(key2);

Upvotes: 2

Views: 2302

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206102

await (besides Modules) is only valid inside an async function. So let's create an Async IIFE

const url = "https://jsonplaceholder.typicode.com";
const getJson = async url => await fetch(url).then(res => res.json());

;(async () => { // Async IIFE
    
  const getJson1 = await getJson(`${url}/users/1`);
  if (!getJson1.id) throw new Error('No ID');
  const getJson2 = await getJson(`${url}/todos/${getJson1.id}`);
  console.log(getJson2);

})();

console.log("PS: I don't wait for the above to finish");

If you know the paths upfront you could go for Promise.all:

const getJson = (url) => fetch(url).then(res => res.json());

Promise.all([
  getJson("https://jsonplaceholder.typicode.com/users/1"),
  getJson("https://jsonplaceholder.typicode.com/todos/1")
]).then((res) => {
  console.log("Both are done!")
  console.log(res[0]);
  console.log(res[1]);
});

Upvotes: 0

hspacheco
hspacheco

Reputation: 154

Something like

const getJson = async (url) => {
  const res = await fetch(url)
  return res.json()
}

const yourFetch = async () => {
  try {
    const json = await getJson('/i/1.json')
    
    if (json.key)  {
      const json2 = await getJson('/i/2.json')
      return json2.key
    }

    throw new Error('No key')
  } catch (err) {
    console.error(err)
  }
}

Upvotes: 3

Related Questions