Skip to content

Instantly share code, notes, and snippets.

@alaingilbert
Last active May 5, 2021 12:48
Show Gist options
  • Save alaingilbert/37bed263996fbf0e8d3993354d5a1f87 to your computer and use it in GitHub Desktop.
Save alaingilbert/37bed263996fbf0e8d3993354d5a1f87 to your computer and use it in GitHub Desktop.
testing async/await in js
<script>
async function run() {
let res = 0;
for (let i = 0; i < 3; i++) {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const json = await response.json();
res += json.id;
}
console.log(res);
}
run();
</script>
<script>
async function run() {
let res = 0;
for (let i = 0; i < 3; i++) {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const json = await response.json();
res += json.id;
}
return res;
}
run().then(res => { console.log(res); });
</script>
<script>
let res = 0;
let promises = [];
for (let i = 0; i < 3; i++) {
let promise = fetch('https://jsonplaceholder.typicode.com/todos/1').then(res => { return res.json(); }).then(data => {
res += data.id;
});
promises.push(promise);
}
Promise.all(promises).then(() => {
console.log(res);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment