Skip to content

Instantly share code, notes, and snippets.

@douglasabnovato
Created December 28, 2021 16:43
Show Gist options
  • Save douglasabnovato/ce0b14c49cd362a9d2341175d5a7e062 to your computer and use it in GitHub Desktop.
Save douglasabnovato/ce0b14c49cd362a9d2341175d5a7e062 to your computer and use it in GitHub Desktop.
promise: fetch, then,catch, finally
function getUser(userId) {
const userData = fetch(`https://api.com/api/user/${userId}`)
.then(response => response.json())
.then(data => console.log(data.name))
.catch(error => console.log(error))
.finally(() => /*{ aviso de fim de carregamento }*/)
}
getUser(1); // "Nome Sobrenome"
@Napiorski
Copy link

Here is the equivalent with async/await:

async function getuser(userId) {
  try {
    const response = await fetch(`https://api.com/api/user/${userId}`)
    const user = await response.json();
  } catch(err) {
    console.error(err);
  }
}

@sferdeveloper
Copy link

sferdeveloper commented May 6, 2023

async functions also have finally , the equivalent should like this:

async function getuser(userId) {
  try {
    const response = await fetch(`https://api.com/api/user/${userId}`)
    const user = await response.json();
  } catch(err) {
    console.error(err);
  }
 } finally {
// aviso de fim de carregamento
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment