Skip to content

Instantly share code, notes, and snippets.

@santoshshinde2012
Created February 12, 2018 06:37
Show Gist options
  • Save santoshshinde2012/2f9a9a34c8e6523b46c97c0de9d3cf5f to your computer and use it in GitHub Desktop.
Save santoshshinde2012/2f9a9a34c8e6523b46c97c0de9d3cf5f to your computer and use it in GitHub Desktop.
Callback vs Promise and Async/Await
// Callback - Example:
// function to alert user name
var greeting = (name) => { alert('Hello ' + name); };
// function to process user input
var processUserInput = (callback) => { var name = prompt('Please enter your name.'); callback(name); };
// start call
processUserInput(greeting);
// Promise - Example:
// function to alert user name
var greeting = (name) => { alert('Hello ' + name); };
// function to process user input
var processUserInput = () => {
return new Promise((resolve, reject) => {
var name = prompt('Please enter your name.');
if(name) resolve(name);
reject(false);
});
};
// start call
processUserInput()
.then(result => greeting(result))
// Promise.all - Example:
var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3])
.then(result => console.log(result))
// Promise.race - Example:
var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'large');
});
var promise4 = new Promise((resolve, reject) => {
setTimeout(resolve, 10, 'small');
});
Promise.race([promise3, promise4])
.then(result => console.log(result))
// Async/Await - Example:
// function to alert user name
var greeting = (name) => { alert('Hello ' + name); };
// function to process user input
var processUserInput = () => {
return new Promise((resolve, reject) => {
var name = prompt('Please enter your name.');
if(name) resolve(name);
reject(false);
});
};
//The word “async” before a function means one simple thing: a function always returns a promise.
async function asyncCall() {
//The keyword await makes JavaScript wait until that promise settles and returns its result.
var result = await processUserInput();
// expected output: "resolved"
greeting(result)
}
// start call
asyncCall();
@hrithik73
Copy link

Very Informative :) Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment