javascript define async function code example
Example 1: how to make an async function
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
}
asyncCall();
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();
Example 3: javascript async await
async function createNewDoc() {
let response = await db.post({});
return await db.get(response.id);
}
async function main() {
try {
let doc = await createNewDoc();
console.log(doc);
} catch (err) {
console.log(err);
}
}
main();