Skip to content

Instantly share code, notes, and snippets.

@wicaker
Created September 17, 2019 03:23
Show Gist options
  • Save wicaker/4df164ae4ea0857acfac5b0ae99f7524 to your computer and use it in GitHub Desktop.
Save wicaker/4df164ae4ea0857acfac5b0ae99f7524 to your computer and use it in GitHub Desktop.
// Write a function which takes a name, and then 400ms later, returns the string "Hello, " + name
// 1. Promise
// 2. Async/Await
// 3. Callback
// using promise
var sayHelloPromise = function (name) {
return new Promise(
function (resolve, reject) {
setTimeout(() => {
var message = "Hello, " + name;
console.log(message)
resolve(message);
}, 400)
}
);
};
// using async await
const sayHelloAsync = async name => {
await new Promise(resolve => setTimeout(resolve, 400));
console.log("Hello, " + name)
return "Hello, " + name;
}
// using callback
const sayHelloCallback = (name, callback) => {
setTimeout(() => {
callback("Hello, " + name);
}, 400);
}
function callback(greeting) {
console.log(greeting)
return greeting
}
sayHelloPromise("catch");
sayHelloAsync("catch");
sayHelloCallback("catch", callback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment