Obtain an array promise containing objects, followed by looping through each object

I am in the process of creating an array named pw_array, copying the contents of pw_subscribers into that array, and then adding new key value pairs to each object in the pw_array from the second promise. I am relatively new to working with promises and struggling to get it right. Currently, when I check console.log(pw_customer) inside the second promise within the getCustomers function, I see the desired output. However, later on when I check console.log(pw_array), it shows the original array.

var pw_array = [];
//the first promise is functioning properly
var getPaywhirlSubscribers = new Promise(function(resolve, reject) {

paywhirl.Subscriptions.getsubscribers({limit:100}, function(error, pw_subscribers) {
        Promise.all(JSON.parse(pw_subscribers).forEach(function(pw_subscriber) {
             pw_array.push(pw_subscriber);
        }))
        // console.log(pw_array);
        return resolve(pw_array);
    });
});

var getGatewayReferences = function(pw_array) {
    return new Promise(function(resolve, reject) {
        Promise.all(pw_array.forEach(function(pw_customer) {
            paywhirl.Customers.getCustomer(pw_customer.customer_id, function(error, customer) {
                pw_customer.phone = customer.phone;
                pw_customer.address = customer.address;
                pw_customer.gateway_reference = customer.gateway_reference;
                // this console.log is returning what I want
                // console.log(pw_customer);
            }); 
        }));
        resolve(pw_array);
        // console.log(pw_array);
    });
};

and the promise chain...

getPaywhirlSubscribers.then(getGatewayReferences).then(function(pw_array) {
  // this console.log is returning the original pw_array with pw_subscribers but not with the appended pw_customer keys
  console.log(pw_array);
});

Answer №1

Your entire codebase can be condensed to

const fetchPaywhirlSubscribers = () => {
  return new Promise((resolve, reject) => {
    paywhirl.Subscriptions.getSubscribers({limit:100}, (error, subscribers) => {
      if (error) {
        reject(error);
      } else {
        resolve(JSON.parse(subscribers));
      }
    });
  });
};

const retrieveGatewayReferences = (promiseArray) => {
  return promiseArray.then((subscribers) => {
    return Promise.all(subscribers.map((subscriber) => {
      return new Promise((resolve, reject) => {
        paywhirl.Customers.getCustomer(subscriber.customer_id, (err, customer) => {
          if (err) {
            reject(err);
          } else {
            resolve(Object.assign({}, subscriber, customer));
          }
        });
      });
    });
  });
};

retrieveGatewayReferences(fetchPaywhirlSubscribers()).then((customerArray) => {
  // handle the customer array accordingly
});

It is worth noting that you could simplify and shorten this even further by utilizing tools that automatically convert node.js-style error-first callback APIs to Promise-based functions. Look into 'promise denodeify' for more information.

Furthermore, you may opt to extract some of the tasks into a .then chain in order to reduce nesting, although this decision is primarily based on aesthetics rather than practicality in my opinion.

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

Securely Upload Files with JavaScript

Are there any methods to utilize javascript or ajax for encrypting file uploads securely? If so, could you provide a sample code snippet or direct me to a functional example? ...

Switch content based on value with Javascript

One of my elements is: <a href="#" type="link" class="button send" classAct="button send" classSel="button send pressed" label="encrypt" title="sendmessage" onclick="add_encryption();">Encrypt</a> When toggled via the JavaScript below, I want ...

What is the best way to transform an array that contains arrays into an array that contains objects with newly-defined properties?

Is there a way to transform this: [[a1, b1], [a2, b2]] into this format? [{x1: a1, y2: b1}, {x2: a2, y2: b2}]? Please note that the properties x1 and x2 are newly introduced with values a1, b1, etc. I attempted to achieve this with the following code sni ...

Dynamic Memory Allocation in C++ using Arrays

When an array is declared on the heap, how can information about the array be obtained? Consider the following code snippet: class Wheel { public: Wheel() : pressure(32) { ptrSize = new int(30); } Wheel(int s, int p) : pressure(p ...

Ajax refuses to process my request for a PUT query

I need to use ajax to send a user-generated email to the controller. $.ajax({ type: 'PUT', url: '/changeEmail?', data: { email: function() { return $('#email').val(); ...

Looking to make changes to a value within a deeply nested array?

How can I update a specific value within a nested array so that the change is reflected in all child and sub-child elements, similar to how selecting a parent node in a tree view selects all its children automatically? https://i.sstatic.net/0f2GE.png http ...

What is the best way to choose a table row <tr> along with the one directly before it?

In the table I have, the first column spans over two rows while the following columns are split into two separate rows. For this table, I need multiple instances of these "doubled rows", which is not a problem so far. To style it with a zebra pattern, I ...

Is it possible to rotate just the camera in ThreeJS by dragging the mouse within the scene?

Currently, I am involved in a project using ThreeJS and I am looking to implement camera rotation using the mouse. Although I have come across OrbitControls that allow me to rotate the camera around a point or object, I am unable to achieve the camera rota ...

Tips on utilizing the window.onload method in conjunction with multiple jQuery click events

I have a dilemma with two buttons in my navigation menu. They are anchor links that switch between tabs on the home page. I want these navigation buttons to activate different tabs when clicked, but I'm struggling with the JavaScript code since I am n ...

Ways to conceal an image by using two functions upon clicking

I have a unique concept in mind - I want to create a functionality where on clicking an image, it would hide the image and start playing content in the background. The content would be an iframe video without a play button, so clicking anywhere on the vi ...

Struggling with developing a straightforward application with Angular-Material

My goal is to develop an application that utilizes the Angular Material navigation bar, as showcased in this example. Being relatively new to AngularJS, I'm facing an issue where my app loads but only displays a blank page. Below is the code snippet ...

Avoiding URL images on 404 errors in frontend applications

My goal is to dynamically implement images (from image_url_1.jpg to image_url_5.jpg) based on a specific URL. While everything works fine, I encounter an issue when a particular image, like "image_url_4.jpg," is not available and results in a 404 Error cau ...

Wave of the figure in three.js

I have sculpted a humanoid figure and now I am attempting to animate the figure waving with its left hand when the waveButton is clicked. I established a hierarchy where the body element is the parent, with leftArm, rightArm, leftLeg, rightLeg, and head as ...

Tips for inheriting and overriding controller methods in AngularJS with Java as the base language:

I have a simple controller and I want to create a new controller that is very similar to it, but without copying too much code. angular.module('test').controller('parentController', parentController); parentController.$inject = [' ...

Issue encountered with the carousel plugin while transitioning to a different page (utilizing Durandal)

I am currently working on a project using the Durandal SPA template, and I have integrated a carousel element into my page: var compositionComplete = function () { $('.testimonials-carousel').carousel({ namespace: "mr-rotato" // ...

Previewing Jquery script with live interactive effect using Javascript

Looking to create a page where a sentence can be written and displayed in a well-designed format on the right using Jquery live preview. However, currently the design only loads after writing and reloading the page. Any suggestions on how to generate the ...

Inject the type into the dependency container

I am managing multiple databases without relying on ORM tools. Here, I will demonstrate an example using Postgres and MSSQL databases with UserQueries. https://i.sstatic.net/GFs5D.png Within my codebase, I have an interface called IDataBase which is impl ...

Interactive JavaScript button that navigates me to a document without the need to click

I'm facing an issue with my small project. I've been learning javascript and managed to create a script that calculates the square of a number provided by the user. var checkIt = function(){ var theNumber = Number(prompt("Please enter a number ...

Obtain Identifiers for LI Data from Dynamic Content

I am currently working on a functionality where the user can assign deliveries to different vans based on the number of vans they have available for the day. However, I am facing an issue where the button does not seem to be functioning properly as it is n ...

What is the best way to capture the inputs' values and store them accurately in my object within localStorage?

Is there a more efficient way to get all the input values ​​and place them in the appropriate location in my object (localStorage) without having to individually retrieve them as shown in the code below? Below is the function I currently use to update ...