// 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);
<script>
const helperPromise = function () {
const promise = new Promise(function (resolve, reject) {
const x = "geeksforgeeks";
const y = "geeksforgeeks";
if (x === y) {
resolve("Strings are same");
} else {
reject("Strings are not same");
}
});
return promise;
};
async function demoPromise() {
try {
let message = await helperPromise();
console.log(message);
} catch (error) {
console.log("Error: " + error);
}
}
demoPromise();
</script>
await new Promise(resolve => setTimeout(resolve, 1000))
// 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.
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));
await new Promise(resolve => setTimeout(resolve, 5000));
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()
// Normal Function
function add(a,b){
return a + b;
}
// Async Function
async function add(a,b){
return a + b;
}