(async () => {
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
...
})();
// (BONUS CODE) await with promise
await new Promise(resolve => setTimeout(resolve, 1000))
console.log('Hello!') // 1 seconds after sended console.log
<script async src="script.js"></script>
const foo = async () => {
await// do something
}
// OR
async function foo() {
await// do something
}
const showPosts = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await response.json();
console.log(posts);
}
showPosts();
//ORIGINAL
//each .then() returns a promisse and can be chained. The .then() will run after the previous one has finished. It emulates an async/await behavior.
fetch('https://jsonplaceholder.typicode.com/users')//fetch the content
.then((response) => response.json())//then use that content and convert it to a javascript object
.then(users => {
const firstUser = users[0];
console.log(firstUser);
return fetch('https://jsonplaceholder.typicode.com/posts?userId=' + firstUser.id);
})//then return the content from posts related to that user ID
.then((response) => response.json())//then use that content and convert it to a javascript object
.then(posts => console.log(posts));//then log the result
//ASYNC/AWAIT
const myAsyncFunction = async () => {//define that this will be asynchronous
const usersResponse = await fetch('https://jsonplaceholder.typicode.com/users');//wait for the fecth result and put it in the variable
const users = await usersResponse.json();//wait for the previous item to be done, transform it into a javascript object and put it in the variable
const secondUser = users[1];
console.log(secondUser);//then log the result
const postsResponse = await fetch('https://jsonplaceholder.typicode.com/posts?userId=' + secondUser.id);//wait for the previous item to be done, wait for the fecth result and put it in the variable
const posts = await postsResponse.json();//wait for the previous item to be done, transform it into a javascript object and put it in the variable
console.log(posts);//then log the result
}
myAsyncFunction();
<script src="demo_async.js" async></script>
//Async function (JAVASCRIPT)
//async function have 1 main purpose:
//Being able to use 'await' in a function
function example() {
return await fetch('https://mysite.com/api'); //error
}
async function smartexample() {
return await fetch('https://mysite.com/api'); //mhmm!
}
// example of async and await in javascript
// First create promise
let myPromise = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Yay, I resolved!')
}, 1000);
});
}
// async without await keyword
async function noAwait() {
let value = myPromise();
console.log(value);
}
// async with await keyword
async function yesAwait() {
let value = await myPromise();
console.log(value);
}
noAwait(); // Prints: Promise { <pending> }
yesAwait(); // Prints: Yay, I resolved!
const asyncExample = async () => {};
function myFunction() {
return Promise.resolve("Hello");
}
fetch('coffee.jpg')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
return response.blob();
}
})
.then(myBlob => {
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
})
.catch(e => {
console.log('There has been a problem with your fetch operation: ' + e.message);
});
// async function example
async function f() {
console.log('Async function.');
return Promise.resolve(1);
}
f();