Skip to content

Instantly share code, notes, and snippets.

@naterexw
Last active April 6, 2018 04:21
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 naterexw/aa217ece08d65739e3ba40221a27526d to your computer and use it in GitHub Desktop.
Save naterexw/aa217ece08d65739e3ba40221a27526d to your computer and use it in GitHub Desktop.
// Async Version
async function callAPIs(){
return doSomething();
}
//Promise Version
function callAPIs(){
return new Promise((resolve,reject)=>{
resolve(doSomething());
})
}
// async function <-> new Promise Object
// await keyword <-> then() method call
// catch block <-> catch() method call
// return keyword <-> resolve() function call
// throw error <-> reject() function call
//
// Async Version
async function callAPIs(){
try{
let res1 = await axios.get("http://example.com")
let res2 = await axios.get(`http://example2.com?key1=${res1.key2}`)
return res2.key2;
}catch(err){
console.log(err);
throw err;
}
}
// Promise version
function callAPIs(){
return new Promise((resolve,reject)=>{
axios.get("http://example.com")
.then((res1)=>axios.get(`http://example2.com?key1=${res1.key2}`))
.then((res2)=> resolve(res2.key2))
.catch((err)=>{
console.log(err);
reject(err);
});
});
}
//Async version
async function callAPIs(){
let res1 = await axios.get("http://example.com")
return res1;
}
// Promise version
function callAPIs(){
return new Promise((resolve,reject)=>{
axios.get('http://example.com')
.then((res1)=>resolve(res1));
});
}
// GET method
axios.get("/users")
.then(res=> console.log(res))
.catch(err=> console.log(err));
// POST method
axios.post("/users",{"id":2,"username":"newUserName"})
.then(res=> console.log(res) )
.catch(err=> console.log(err) );
// DELETE method
axios.delete("/users",{id:3})
.then(res=> console.log(res))
.catch(err=> console.log(err));
// PUT method
axios.put("/users",{"email":"user@user.com","password":"1234"})
.then(res=> console.log(res))
.catch(err=> console.log(res));
// Async version
async function callAPIs(){
try{
let res1 = await axios.get('http://example.com');
return res1;
}catch(err){
console.log(err);
throw err;
}
}
// Promised version
function callAPIs(){
return new Promise((resolve,reject)=>{
axios.get("http://example.com")
.then((res1)=>resolve(res1))
.catch((err)=> reject(err))
});
}
// Async version
async function callAPIs(){
let combinedPromise = Promise.all([axios.get('http://example1.com'),
axios.get('http://example2.com')]);
let responses = await combinedPromise;
return responses;
}
// Promised version
const p1 = new Promise((resolve, reject) => {
setTimeout(resolve, 1000, 'one');
});
const p2 = new Promise((resolve, reject) => {
setTimeout(resolve, 2000, 'two');
});
Promise.all([p1, p2])
.then(values => console.log(values))
.catch(err => console.log(err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment