xxxxxxxxxx
// example of promise and async in javascript
// 1) promise: we need to write new keyword to create promise
function withConstructor(num){
return new Promise((resolve, reject) => {
if (num === 0){
resolve('zero');
} else {
resolve('not zero');
}
});
}
withConstructor(0)
.then((resolveValue) => {
console.log(` withConstructor(0) returned a promise which resolved to: ${resolveValue}.`);
});
// Output: withConstructor(0) returned a promise which resolved to: zero.
// 2) async: we don't need to write new keyword to create promise
async function withAsync(num){
if (num === 0) {
return 'zero';
} else {
return 'not zero';
}
}
withAsync(100)
.then((resolveValue) => {
console.log(` withAsync(100) returned a promise which resolved to: ${resolveValue}.`);
})
// Output: withAsync(100) returned a promise which resolved to: not zero.
xxxxxxxxxx
// server.js
function square(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(Math.pow(x, 2));
}, 2000);
});
}
async function layer(x)
{
const value = await square(x);
console.log(value);
}
layer(10);
xxxxxxxxxx
async function myFetch() {
let response = await fetch('coffee.jpg');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.blob();
}
myFetch().then((blob) => {
let objectURL = URL.createObjectURL(blob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
}).catch(e => console.log(e));
xxxxxxxxxx
we can only use await keyword before a function that
returns either a promise or is itself async.
Note: we can use async function or function returning
a Promise with .then()
xxxxxxxxxx
// Normal Function
function add(a,b){
return a + b;
}
// Async Function
async function add(a,b){
return a + b;
}