Skip to content

Instantly share code, notes, and snippets.

@hugohabel
Last active February 20, 2022 02:11
Show Gist options
  • Save hugohabel/f2404f583eba89201bf4d612c730898b to your computer and use it in GitHub Desktop.
Save hugohabel/f2404f583eba89201bf4d612c730898b to your computer and use it in GitHub Desktop.
Basics of a Promise
const https = require('https');
// Constants
const URL = 'https://fakestoreapi.com/products';
const requestParams = {
url: URL
};
/**
* Get products list.
*
* @param {Object} requestParams - The URL of the API
*/
function getProductsList(requestParams) {
const { url } = requestParams; // Get endpoint URL
let productsList = [];
// Get products
const getProducts = new Promise(function(resolve, reject) {
let products = '';
const request = https.get(url, (response) => {
response.on('data', (data) => {
products += data;
});
response.on('end', () => {
resolve(JSON.parse(products));
});
response.on('error', (error) => {
reject(error);
});
});
});
// Promise handlers - Promise execution doesn't need a `.then` method call for it to execute.
getProducts
.then((data) => {
data.forEach((product) => {
productsList.push(product);
});
console.log(productsList);
}, (error) => {
throw error;
})
.catch((error) => {
console.log(error);
});
}
getProductsList(requestParams);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment