javascript await promise 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: js async await
async function myFunction(){
await ...
}
const myFunction2 = async () => {
await ...
}
const obj = {
async getName() {
return fetch('https://www.example.com');
}
}
class Obj {
async getResource {
return fetch('https://www.example.com');
}
}
Example 3: js await
const a = async () => {
await b();
c();
};
Example 4: await javascript
The await operator is used to wait for a Promise. It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.
Example 5: async await
async function showAvatar() {
await setTimeout(resolve, 3000);
}
showAvatar();
Example 6: async and await
function delayResult() {
return new Promise(resolve => {
setTimeout(() => {
resolve(‘Done’);
}, 5000)
})
}
async function getResult() {
let result = await delayResult();
return result;
}
getResult();