Last active
February 20, 2022 02:11
-
-
Save hugohabel/f2404f583eba89201bf4d612c730898b to your computer and use it in GitHub Desktop.
Basics of a Promise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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