Skip to content

Instantly share code, notes, and snippets.

@chetanraj
Created August 15, 2021 12:44
Show Gist options
  • Save chetanraj/1e4b92d12e5254890985f6f4c405a58e to your computer and use it in GitHub Desktop.
Save chetanraj/1e4b92d12e5254890985f6f4c405a58e to your computer and use it in GitHub Desktop.
// get books
const getBookByName = (name) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ name: 'Art of War', author: 'Sun Tsu', ISBN: 9780140439199 });
}, 500);
});
};
// check if that book exists
checkIfBookExists = (ISBN) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ stock: 10, ISBN: 9780140439199 });
}, 500);
});
};
// hit BooksRun API - To get the new, used and rent price
getTheBookPrice = (ISBN) => {
return new Promise((resolve, reject) => {
const URL = `https://booksrun.com/api/v3/price/buy/${ISBN}?key=${process.env.API_KEY}`;
fetch(URL)
.then((response) => {
resolve(response.json());
})
.catch((err) => {
reject(err);
});
});
};
// Using Promise
getBookByName('Art of War').then((book) => {
if (book) {
checkIfBookExists(book.ISBN).then((data) => {
if (data.stock > 0) {
getTheBookPrice(data.ISBN).then((response) => {
console.log(response);
});
}
});
} else {
console.log('Book not found!');
}
});
// Using async/await
const beingAsync = async () => {
const book = await getBookByName('Art of War');
const { stock } = await checkIfBookExists(book.ISBN);
if (stock > 0) {
const response = getTheBookPrice(book.ISBN);
console.log(`Book price is $${response.offers.booksrun.new.price}!`);
} else {
console.log('Book not found!');
}
};
beingAsync();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment