Creating a new file for a promise function

Initially, I managed to make this function work within a single file. However, I prefer organizing my code by splitting it into multiple files.

// library.js file
module.exports = {
    get: () =>{
        return new Promise((reject, resolve) =>{
            return resolve(https.get('https://api.instagram.com/v1/users/self/?access_token=' + cred.access_token, (res) =>{
                res.setEncoding('utf8');
                return res.on('data', (data) =>{
                    return data;
                });
            }));
        });
    }
}

Initially, when I tried logging this, nothing was displayed.

// server.js file
igLib.get().then((data) => {
    console.log("testing: " + data);
})

However, to my surprise, when I simply logged..

// server.js file
console.log(igLib.get());

I somehow managed to retrieve the data without using res.setEncoding('utf8').

Do you have any suggestions on what steps to take next?

Update: After struggling with making the promise work and appreciating those who provided valuable insights, I decided to utilize the request-promise module as an alternative solution. Here's the revised approach:

// library.js file
var instagramSelfUrl = 'https://api.instagram.com/v1/users/self/?access_token=' + cred.access_token;

module.exports = {
    get: () =>{
        return rp(instagramSelfUrl).then((res) =>{
            return res;
        });
    }
}

Here is where I include the console.log statement:

// server.js file
    igLib.get().then((data) =>{
    console.log(data);
});

It's simpler, more efficient, and functional. If there are alternative solutions apart from relying on external modules, please feel free to share your thoughts and recommendations! Thank you for all the assistance and advice provided!

Answer №1

It is essential that the promise you establish resolves with the data retrieved from the response.

// library.js file
const https = require('https');
const instagramSelfUrl = 'https://api.instagram.com/v1/users/self/?access_token=' + cred.access_token;

module.exports = {
    get: () => new Promise(function (resolve, reject) {
        https.get(instagramSelfUrl, res => {
            var chunks = [];
            res.setEncoding('utf8');
            res.on('data', chunk => chunks.push(chunk));
            res.on('end', () => resolve(chunks.join('')));
        });
    })
};

However, the code above lacks completeness and robustness. For instance, errors in the request or a response status of 500 should result in rejecting the promise, but there is no error handling implemented. Furthermore, if the response is not actually in UTF-8 format, the data may be decoded incorrectly. These are just a couple of the evident issues present.

The process of converting HTTP requests into promises has been successfully addressed by existing solutions. It is highly recommended to utilize one of the libraries available instead of creating custom code that replicates common mistakes.

const request = require('request-promise');
const instagramSelfUrl = 'https://api.instagram.com/v1/users/self/?access_token=' + cred.access_token;

module.exports = {
    get: () => request(instagramSelfUrl)
};

Now, the function is comprehensive and operates correctly, even under challenging circumstances. Additionally, the revised code is so concise that it may not warrant a separate function at all.

Answer №2

It appears that your data retrieval process is not working correctly. You may want to consider the following code snippet:

// library.js file
module.exports = {
    get: () =>{
        return new Promise((reject, resolve) =>{
            https.get('https://api.instagram.com/v1/users/self/?access_token=' + cred.access_token, (res) =>{
                res.setEncoding('utf8');
                return res.on('data', (data) =>{
                    return resolve(data);
                });
            });
        });
    }
}

Answer №3

If you want to achieve something similar, consider the following approach:

module.exports = {
    get: () =>{
        return new Promise((resolve, reject) =>{
            https.get('https://api.instagram.com/v1/users/self/?access_token=' + cred.access_token, (res) =>{
                res.setEncoding('utf8');
                res.on('data', (data) =>{
                    resolve(data);
                });
            }).on('error', (e) => reject(e))
        });
    }
}

To learn more about promises, check out this link: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for receiving updates while subscribing in ReactReduxContext.Consumer?

I am currently seeking a solution to staying updated on changes to a stored value in the Redux store by subscribing. I have attempted the following method: <ReactReduxContext.Consumer> {({store}) => { console.log('store:& ...

Fixed position toolbar within a container positioned beside a dynamically sized sidebar navigation

I'm trying to figure out how to create a fixed toolbar that fills the remaining width of the page when a side nav is collapsible. Setting the width to 100% causes it to overflow the page due to the dynamic nature of the side nav. Using calc() isn&apos ...

Issue with AngularJS: error:areq Invalid Argument

<!DOCTYPE html> <html ng-app> <body data-ng-controller="SimpleController"> <div class="container"> Title: <br/> <input type="text" ng-model="title" />{{title}} <br/> ...

What is the best way to send an object from the front end to the backend using res.send?

In my current project, I am establishing communication between the frontend and backend. The process involves the backend sending an expression to the frontend for computation, after which the computed answer needs to be sent back to the backend. For exam ...

Learn how to serialize and submit all form components within a specified element using AJAX

I am attempting to serialize and post all form elements that may originate from either within a <form> element, or any other elements such as divs, trs, etc. In essence, my form can be structured in two ways: <form id="frm1"> Name: ...

Javascript puzzle - I have 99 obstacles

...but a malfunction isn't one. Hey there, I am new to learning so I apologize for the seemingly simple question. I'm experimenting with a theoretical logic statement that would work using javascript. For instance: if (issues == 99) { malfunct ...

Enhancing Your Model with Additional Details using Angular Formly

I have been utilizing Angular Formly to display forms generated from the JSON response received from services. However, I have a few inquiries. Is it feasible to retrieve data in a field (templateOptions.label, for instance) to include in the model? ...

Searching for a document using the $eq operator in MongoDB within the context of Next.js - what is

In my Next.js code, I am fetching a document from MongoDB using a unique slug. Here is the code snippet: export async function getStaticProps(context) { const postSlug = context.params.postPage; const { db } = await connectToDatabase(); const posts ...

ReactJs: How useEffect is invoked before onClick function in NextJS

I am facing an issue with a button in my Next project. Here is the code for the button: <Button minWidth={'140px'} onClick={() => exec(scope)} >Save</Button> When this button is clicked, it triggers the following function: c ...

preventing the page from scrolling whenever I update my Angular view

Whenever I update a part of my model that is connected to my view, my page automatically scrolls. I suspect that the page scrolling is triggered by the view updates. How can I stop this from happening? For instance, here is an example involving a dropdown ...

Tips for seamlessly transitioning the background of Google Maps into view as you scroll down the page

I have a unique background with a Google Map. It loads perfectly in the right place when I open the page, but as I scroll down, it disappears from view. Is there a way to keep the Google map constantly in the background, even when scrolling? This is my cu ...

Transform a span into a div while retaining its content and styles, ensuring compatibility with Internet Explorer

Is there a reliable JavaScript method to convert a span into a div while preserving its contents and the original classes of the span? The classes are pre-set, so hardcoding should be possible. <span class="my class"> <p class="conten ...

Building a NodeJS/Express application that utilizes the PUT method and body parser, with a scenario where

I created a basic rest api for a blog. Here is the code snippet from the main file: var port = process.env.PORT || 8080; var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser ...

Struggling to loop through a child in Firebase real-time database?

I'm struggling to retrieve a nested child from my database with the following structure https://i.stack.imgur.com/ZDs38.png I am attempting to get the URI from the Gallery object. When I log in, I can see this in the console https://i.stack.imgur.c ...

Occasionally, the system may mistakenly flag a password as invalid even though it is indeed correct

To ensure the password meets certain criteria, it must start with a Z, have at least 8 characters, and contain an asterisk *. Take a look at this validating function: function validatePassword() { var strPassword; //Prompt user to enter pas ...

PHP Multiple Uploads is a feature that allows users to

I'm currently attempting to utilize the dropzone JS plugin in combination with PHP for the purpose of uploading multiple files and then displaying each file's URL. Here is my progress so far: $upload_dir = 'files'; for($i=0; $i&l ...

The reduce function is displaying an undefined result

Check out this code snippet: const filterByType = (target , ...element) => { return element.reduce((start, next) =>{ if(typeof next === target){ start.push(next) } } , []) } I'm trying to achieve a specific g ...

NodeJS header not functioning properly for file names

Whenever I try to download uploaded files, I have to change the file name to its actual name stored in the database. The code below should work for this purpose, but it's not working as expected. Here is the code snippet: res.setHeader('Content ...

"Integrating React with Express.js: A Step-by-Step

I've successfully set up the basic files for express using express generator. I'm looking to incorporate React into my express project and integrate it with Express. What steps do I need to take to achieve this? ...

What is the best method for transforming a stream into a file with AngularJS?

Currently, I have a server returning a file stream (StreamingOutput). My goal is to convert this file stream into an actual file using AngularJS, javascript, JQuery, or any other relevant libraries. I am looking to display the file in a <div> or ano ...