Last active
July 21, 2022 14:23
-
-
Save rimivan/86214bb9db92d8756f559ea961a664f1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const random = () => { | |
return Promise.resolve(Math.random()*10) | |
} | |
'Bad Promise Code 💩' | |
const sumRandomAsyncNums = () => { | |
let first; | |
let second; | |
let third; | |
return random() | |
.then(v => { | |
first = v; | |
return random(); | |
}) | |
.then(v => { | |
second = v; | |
return random(); | |
}) | |
.then(v => { | |
third = v; | |
return first + second + third | |
}) | |
.then(v => { | |
console.log(`Result ${v}`) | |
}); | |
} | |
'Good Promise Code ✅' | |
const sumRandomAsyncNums = async() => { | |
const first = await random(); | |
const second = await random(); | |
const third = await random(); | |
console.log(`Result ${first + second + third}`); | |
if (await random()) { | |
// do something - non si sa a cosa serve | |
console.log("Dentro IF") | |
} | |
// promise all: Promise.all(iterable) return a promise when all promises are resolved | |
// Reference: https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Promise | |
const randos = Promise.all([ | |
random(), | |
random(), | |
random() | |
]) | |
for(const r of await randos) { | |
console.log(r) | |
} | |
} | |
sumRandomAsyncNums() | |
Example from js.info | |
async function showAvatar() { | |
// legge il nostro JSON | |
let response = await fetch('/article/promise-chaining/user.json'); | |
let user = await response.json(); | |
// legge l'utente GitHub | |
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment