await async nodejs code example
Example 1: nodejs promise async
// 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);
Example 2: nodejs promise async
// Normal Function
function add(a,b){
return a + b;
}
// Async Function
async function add(a,b){
return a + b;
}
Example 3: async await
async function f() {
try {
let response = await fetch('/no-user-here');
let user = await response.json();
} catch(err) {
// catches errors both in fetch and response.json
alert(err);
}
}
f();
Example 4: define async function in node js
async function name([param[, param[, ...param]]]) {
statements
}
Example 5: await async
function afterPrintSave() {
Xrm.Page.data.save().then(
function () {
resolve();
},
function (err) {
resolve(alert(err.message));
}
);
}
Example 6: async await js
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);
});