async await promise javascript 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: async await javascript
function hello() {
return new Promise((resolve,reject) => {
setTimeout(() => {
resolve('I am adam.');
}, 2000);
});
}
async function async_msg() {
try {
let msg = await hello();
console.log(msg);
}
catch(e) {
console.log('Error!', e);
}
}
async_msg(); //output - I am adam.
Example 3: js async await
/* Notes:
1. written like synchronous code
2. compatible with try/catch blocks
3. avoids chaining .then statements
4. async functions always return a promise
5. function pauses on each await expression
6. A non promise value is converted to
Promise.resolve(value) and then resolved
*/
// Syntax
// Function Declaration
async function myFunction(){
await ... // some code goes here
}
// Arrow Declaration
const myFunction2 = async () => {
await ... // some code goes here
}
// OBJECT METHODS
const obj = {
async getName() {
return fetch('https://www.example.com');
}
}
// IN A CLASS
class Obj {
// getters and setter CANNOT be async
async getResource {
return fetch('https://www.example.com');
}
}
Example 4: nodejs promise async
// Normal Function
function add(a,b){
return a + b;
}
// Async Function
async function add(a,b){
return a + b;
}
Example 5: javascript async await
// The await operator in JavaScript can only be used from inside an async function.
// If the parameter is a promise, execution of the async function will resume when the promise is resolved
// (unless the promise is rejected, in which case an error will be thrown that can be handled with normal JavaScript exception handling).
// If the parameter is not a promise, the parameter itself will be returned immediately.[13]
// Many libraries provide promise objects that can also be used with await,
// as long as they match the specification for native JavaScript promises.
// However, promises from the jQuery library were not Promises/A+ compatible until jQuery 3.0.[14]
async function createNewDoc() {
let response = await db.post({}); // post a new doc
return await db.get(response.id); // find by id
}
async function main() {
try {
let doc = await createNewDoc();
console.log(doc);
} catch (err) {
console.log(err);
}
}
main();
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);
});