Skip to content

Instantly share code, notes, and snippets.

@yleflour
Created February 7, 2022 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yleflour/881e1c194e1c63f591c6b565ad1f50d8 to your computer and use it in GitHub Desktop.
Save yleflour/881e1c194e1c63f591c6b565ad1f50d8 to your computer and use it in GitHub Desktop.
Callback / Promises / Async
// Callback
const asyncPowWithCallback = (arg1, timeout, callback: (error, value) => void) => {
setTimeout(() => {
callback(null, arg1*arg1);
}, timeout);
}
const value = asyncPowWithCallback(2, 100, (error, value) => {
console.log("value1");
});
const value2 = asyncPowWithCallback(3, 100, (error, value) => {
console.log("value2");
});
console.log("Done");
asyncPowWithCallback(2,100, (error, value) => {
asyncPowWithCallback(value, 100, (error, value2) => {
console.log(value2)
})
})
// Promises
const asyncPowWithPromise = (arg1, timeout) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(arg1*arg1);
}, timeout);
});
};
const asyncPowPromisifiedFromCallback = (arg1, timeout) => {
return new Promise((resolve, reject) => {
asyncPowWithCallback(arg1, timeout, (error, value) => {
if (error) {
reject(error);
} else {
resolve(value);
}
});
});
};
let valueStep2 = null;
const valPromise = asyncPowWithPromise(2, 100)
.then(value => {
valueStep2 = value;
return asyncPowWithPromise(value, 100)
})
.then(value => asyncPowWithPromise(value, 100))
.then((value) => {
console.log(value);
console.log(valueStep2);
})
;
// Async await
const asyncMain = async () => {
const value1 = await asyncPowWithPromise(2, 100);
const value2 = await asyncPowWithPromise(value1, 100);
const value3 = await asyncPowWithPromise(value2, 100);
console.log(value1);
console.log(value3);
const [val1, val2] = await Promise.all([
asyncPowWithPromise(2, 100),
asyncPowWithPromise(3, 100),
]);
console.log(val1, val2);
}
asyncMain();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment