Skip to content

Instantly share code, notes, and snippets.

@Gaurav8757
Last active March 23, 2026 11:04
Show Gist options
  • Select an option

  • Save Gaurav8757/09fdfc68fbf734256acbf47ce3857c8a to your computer and use it in GitHub Desktop.

Select an option

Save Gaurav8757/09fdfc68fbf734256acbf47ce3857c8a to your computer and use it in GitHub Desktop.
Callback, Promise and Async / Await
// Callbacks
function user(callback1){
let name = 'Gaurav';
setTimeout(()=> {
callback1(name); // if callback not take argument give undefined
}, 2000);
}
function userAge(name, callback2){
let age = name + ' age is 24.';
setTimeout(()=> {
callback2(age);
}, 2000);
}
// callback runs from here
user((name) => {
console.log(name) // If 1st dn not pass name in callback1(name) >>> it print undefined;
return userAge(name, (age) => {
console.log(`${age}`)
});
});
// Promise
function userPromise(){ // parent scope
let name = 'Gaurav';
return new Promise((resolve, reject) => { // parent
setTimeout(()=> {
resolve(name); // lexical scope parent ka scope
}, 2000);
})
}
function userAgePromise(name){
let age = name + ' age is 24.';
return new Promise((resolve, reject) => { // parent
setTimeout(()=> {
resolve(age); // lexical scope parent ka scope
}, 2000);
})
}
// Promise chain then . catch .finally
// 1. >>
userPromise().then((name) => userAgePromise(name)).then((age) => console.log(age)).catch((err) => console.log(err)).finally(() => console.log('finally completed'));
// 2. >>
userPromise().then((name) => {
console.log(name);
return userAgePromise(name);
}).then((age) => {
console.log(age);
}).catch((err) => {
console.log(`Error Happened: ${age}`);
}).finally(() => {
console.log('Finaly reached end of promise page')
});
// Async / Await
async function asyncCodeUser(){
const name = await userPromise();
console.log(name);
const age = await userAgePromise(name);
console.log(age);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment