Normal Promise
./hello.js
function sendRequest() {
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve("Lintao")
}, 2000)
});
}
let promise = sendRequest();
promise.then(function(username) {
console.log(username)
})
Change to Await
./hello-await.js
function sendRequest() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("Lintao");
}, 2000);
});
}
// must put await inside async function
async function getUsername() {
// put await in front of a function which returns a Promise object
console.log(await sendRequest());
}
getUsername()
Error handling
./hello-await-error-handling.js
function sendRequest() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject("Lintao");
}, 2000);
});
}
async function getUsername() {
// put inside try..catch block
try {
console.log(await sendRequest());
} catch (error) {
console.log(`error: ${error}`);
}
}
getUsername();
With Fetch
./hello-await-fetch.js
function sendRequest() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject("Lintao");
}, 2000);
});
}
async function getUsername() {
// put inside try..catch block
try {
let username = await fetch('https://jsonplaceholder.typicode.com/users')
username = await username.json()
console.log(username);
} catch (error) {
console.log(`error: ${error}`);
}
}
getUsername();