javascript async await code example

Example 1: async await catch error

async function f() {

  try {
    let response = await fetch('/no-user-here');
    let user = await response.json();
  } catch(err) {
    // catches errors both in fetch and response.json
    alert(err);
  }
}

Example 2: async await

const data = async ()  => {
  const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  
  console.log(await got.json())
}

data();

Example 3: async await

async function showAvatar() {

  // read our JSON
  let response = await fetch('/article/promise-chaining/user.json');
  let user = await response.json();

  // read github user
  let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
  let githubUser = await githubResponse.json();

  // show the avatar
  let img = document.createElement('img');
  img.src = githubUser.avatar_url;
  img.className = "promise-avatar-example";
  document.body.append(img);

  // wait 3 seconds
  await new Promise((resolve, reject) => setTimeout(resolve, 3000));

  img.remove();

  return githubUser;
}

showAvatar();

Example 4: async await promise all javascript

let characterResponse = await fetch('http://swapi.co/api/people/2/')
let characterResponseJson = await characterResponse.json()
let films = await Promise.all(
  characterResponseJson.films.map(async filmUrl => {
    let filmResponse = await fetch(filmUrl)
    return filmResponse.json()
  })
)
console.log(films)

Example 5: how to make an async function

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

//async function:
async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();

Example 6: javascript async await

// The await operator in JavaScript can only be used from inside an async function.
// If the parameter is a promise, execution of the async function will resume when the promise is resolved
// (unless the promise is rejected, in which case an error will be thrown that can be handled with normal JavaScript exception handling).
// If the parameter is not a promise, the parameter itself will be returned immediately.[13]

// Many libraries provide promise objects that can also be used with await,
// as long as they match the specification for native JavaScript promises.
// However, promises from the jQuery library were not Promises/A+ compatible until jQuery 3.0.[14]

async function createNewDoc() {
  let response = await db.post({}); // post a new doc
  return await db.get(response.id); // find by id
}

async function main() {
  try {
    let doc = await createNewDoc();
    console.log(doc);
  } catch (err) {
    console.log(err);
  }
}
main();

Tags:

Php Example