xxxxxxxxxx
async function name([param[, param[, param]]]) {
statements
}
xxxxxxxxxx
// Old School Javascript Invoke
(async function() {
await someAsyncFunction();
})();
//New ES6 Javascript Invoke
(async () => {
await someAsyncFunction();
})();
//Example (async & await)
function delayResult() {
return new Promise(resolve => {
setTimeout(() => {
resolve(‘Done’);
}, 5000)
})
}
async function getResult() {
let result = await delayResult();
return result;
}
getResult();
//New Example
const data = async () => {
const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log(await got.json())
}
data();
xxxxxxxxxx
const yourAsyncFunction = async () => {
// do something asynchronously and return a promise
return result;
}
anArray.forEach(async item => {
// do something asynchronously for each item in 'anArray'
// one could also use .map here to return an array of promises to use with 'Promise.all()'
});
server.getPeople().then(async people => {
people.forEach(person => {
// do something asynchronously for each person
});
});
xxxxxxxxxx
//Async function (JAVASCRIPT)
//async function have 1 main purpose:
//Being able to use 'await' in a function
function example() {
return await fetch('https://mysite.com/api'); //error
}
async function smartexample() {
return await fetch('https://mysite.com/api'); //mhmm!
}
xxxxxxxxxx
JS
copy
const doSomethingAsync = () => {
return new Promise(resolve => {
setTimeout(() => resolve('I did something'), 3000);
});
};