Skip to content

Instantly share code, notes, and snippets.

@anbnyc
Created February 25, 2019 20:28
Show Gist options
  • Save anbnyc/98a273d24eff9552cf8461db0852c56f to your computer and use it in GitHub Desktop.
Save anbnyc/98a273d24eff9552cf8461db0852c56f to your computer and use it in GitHub Desktop.
Async JavaScript examples
function asyncWithCallbacks(callback){
getApiUrl(apiName, function(err1, url){
if(err1) throw new Error(err1);
callApi(url, function(err2, data){
if(err2) throw new Error(err2);
writeDataToServer(data, function(err3, response){
if(err3) throw new Error(err3);
console.log('welcome to the third circle of callback hell.')
callback(response);
})
})
}
}
function asyncWithPromises(callback){
getApiUrl(apiName)
.then(url => callApi(url))
.then(data => writeDataToServer(data))
.then(response => {
console.log('this is definitely better.')
callback(response) // but this is still needed, I think
})
.catch(err => {
console.log(err);
})
}
async function asyncWithAwait(){
try{
const url = await getApiUrl(apiName);
const data = await callApi(url);
const response = await writeDataToServer(data);
return response;
} catch (err) {
console.log(error);
}
}
const p1 = new Promise(function(resolve, reject){
setTimeout(() => {
resolve(1);
}, 1000)
})
const p2 = new Promise(function(resolve, reject){
setTimeout(() => {
resolve(2);
}, 2000)
})
const p3 = new Promise(function(resolve, reject){
setTimeout(() => {
resolve(3);
}, 3000)
})
const f1 = async () => {
return await p1
}
const f2 = async () => {
return await p2
}
const f3 = async () => {
return await p3
}
const waitForPromises = async () => {
return await Promise.all([f1(), f2(), f3()])
}
const syncFunc = () => [8,9,10];
const controller = async () => {
const s = new Date().getTime();
const results = await waitForPromises()
const syncResults = syncFunc();
console.log(new Date().getTime() - s)
console.log(results, syncResults)
return syncResults;
}
module.exports = {
waitForPromises,
controller
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment