Skip to content

Instantly share code, notes, and snippets.

@ifindev
Created February 14, 2021 09:22
Show Gist options
  • Select an option

  • Save ifindev/493cc08aaf3a64f1e7e864417cc6a1b8 to your computer and use it in GitHub Desktop.

Select an option

Save ifindev/493cc08aaf3a64f1e7e864417cc6a1b8 to your computer and use it in GitHub Desktop.
Promises and Asynchronous Javascript
// login api which accepts username and password and return a promise
// timeout for simulating request time delay
let login = (username, password) => {
let validUsername = "ifindev";
let validPassword = "1234567";
return new Promise((resolve, reject) => {
setTimeout( () => {
if(username === validUsername && password === validPassword) {
resolve("login success!");
} else {
reject("login failed!");
}
} ,5000);
});
};
// Valid login
login("ifindev", "1234567")
.then(result => console.log(result))
.catch(() => console.log("sorry... login failed"));
// Invalid login
login("visitor", "randompw")
.then(result => console.log(result))
.catch(() => console.log("sorry... login failed"));
'use strict';
let state = true;
// Create a fake Fetch API request that returns a promise
let fetch = new Promise((resolve, reject) => {
setTimeout( () => {
if(state === true) {
resolve({
name:"ifindev",
dream:"React developer"
});
} else {
reject(new Error("error"));
}
} ,5000)
});
//then and catch the promise success and error
fetch
.then(result => console.log(result))
.catch(err => console.log(err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment