Issue with array push not working within nested Promise

I recently encountered an issue with my Express API route that retrieves an artist's details along with an array of releases for that artist.

My current goal is to iterate over this array, extract each URL, and then make additional API calls to retrieve more data. I am trying to store the responses in an array which will be returned as a response to the front end.

However, I noticed that when I log the array, it appears to be empty.

I am utilizing the request-promise library from npm for this purpose.

Do you think my approach is correct? I suspect that I may need to ensure that all promises are resolved before proceeding with further execution, but I'm not entirely sure how to do so.

route.get('/search', (req, res) => {
    const artist = req.query.artist || '';
    let releases = [];

    rp.get(`https://api.discogs.com/database/search?artist=${artist}&type=release&format=Vinyl&per_page=5&page=1`)
        .then(({results}) => results.map(({resource_url}) => resource_url))
        .then((resource_urls) => resource_urls.map((resource_url) => rp.get(resource_url).then((release) => releases.push(release))))
        .then(() => console.log(releases))
        .catch((err) => console.log(err))
});

Answer №1

If you utilize the `Promise.all` method within the chain, you can avoid using the previously declared `releases` variable:

route.get('/search', (req, res) => {
    const artist = req.query.artist || '';

    rp.get(`https://api.discogs.com/database/search?artist=${artist}&type=release&format=Vinyl&per_page=5&page=1`)
        .then(({results}) => results.map(({resource_url}) => resource_url))
        .then((resource_urls) => Promise.all(resource_urls.map((resource_url) => rp.get(resource_url)))
        .then((releases) => console.log(releases))
        .catch((err) => console.log(err))
});

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

Capturing HTTP response notifications

Currently, I am in the process of developing a Node web application with Express. My goal is to maintain a DRY (Don't Repeat Yourself) approach throughout the project, which includes automatically acquiring and releasing the database connection for ea ...

Arranging elements on top of a fixed element using JavaScript and CSS

Currently, I am implementing Javascript code that adds a div to the body of pages. The purpose of this div is to always stay at the top of the document or window, regardless of the page's design and content. Everything was functioning correctly until ...

Utilize the power of jQuery to easily toggle visibility of an overlay

I have successfully implemented JQuery to show and hide my overlay with great success. Now, I am interested in adding animations to enhance the user experience. After reviewing the jq documentation, I found some cool animations that can be easily integrate ...

Basic Node.js messaging application excluding the use of socket.io

Recently, I've delved into learning Node.js and embarked on creating a basic chat application. It appears that socket.io is the go-to option for most developers, but I'm keen on grasping the concept from a more foundational standpoint using GET a ...

Backand - How can I display the contents of variables using console.log() within Security Actions?

Is there a way to utilize console.log() in Backand, specifically within the server side functions like those found under Security & Auth > Security Actions? I have checked the Read.me which suggests using 'console.log(object) and console.error(object) ...

JQuery Validation - Implementing real-time validation on button click instead of form submission

I am currently attempting to use JQuery Validation with WebForms/html. I have simplified the HTML code below, displaying only the necessary elements: <input id="txtEmail"/> <input id="txtTicketID"/> <a id="create" href="#">Create a new t ...

Designing multiple button actions in v-card-actions in Vuetify: A step-by-step guide

Trying to streamline the v-card-actions on my Vuetify v-cards. My aim is to center the test button within the v-card and position it above the like and share "footer" buttons. I want the like and share footer buttons to be at the bottom of the v-card with ...

Leveraging Multiple MongoDB Databases in Meteor.js

Can 2 Meteor.Collections fetch data from separate MongoDB database servers? Dogs = Meteor.Collection('dogs') // mongodb://192.168.1.123:27017/dogs Cats = Meteor.Collection('cats') // mongodb://192.168.1.124:27017/cats ...

How to stop parent event propagation in jQuery

I am facing a frustrating issue with my code. Every time I toggle a checkbox, the parent element's click event also triggers. I have experimented with various solutions like: event.stopImmediatePropagation(); event.stopPropagation(); event.preventD ...

Fetching a Wikipedia page using AJAX or the fetch() method

I am currently attempting to dynamically retrieve a Wikipedia webpage within the browser in order to utilize XSLTProcessor for further processing of the XHTML content. Unfortunately, my efforts have been unsuccessful as Wikipedia is not sending the necess ...

Failing to verify the presence of specific text within a dropdown menu using Selenium

Previously, I successfully implemented this code, however, the HTML/CSS for the dropdown has since changed and now I am unable to get it to function correctly. Below is the structure for the dropdown code, with specific text highlighted that I am trying t ...

how to use serializeArray() to create an array with named keys

I am struggling with a piece of HTML code : <input type="checkbox" name="search-form[filters][category][12]" value="cat-12" autocomplete="off" checked="checked" /> <input type="checkbox" name="search-form[filters][category][14]" value="cat-14" au ...

Discover the method of invoking a Firebase Cloud Function which utilizes ExpressJS in conjunction with cloud_functions

I have integrated a Firebase Cloud Function with ExpressJS that I want to access from my mobile application. Instead of making a simple http request, I am considering using the cloud_firestore package in Dart/Flutter as it may handle authentication more s ...

Troubles arise when trying to load AngularJS using RequireJS within the application

I am currently developing a NodeJS application that utilizes AngularJS for its front-end. Additionally, I am integrating RequireJS to handle the loading of JavaScript dependencies and then initialize the Angular app. Here is my approach: Inside my HTML fi ...

Send data to the client in Express using stream buffering

My request handler currently sends files from MongoDB (GridFS) to the client using a variable called data, which stores the content in memory. I am looking to improve this process by implementing streaming mode and sending the file in chunks to the client. ...

Concealing a hyperlink depending on the value chosen in a dropdown menu

Looking for guidance on how to use jQuery to read the current value of a drop-down list and hide a specific link based on that value. The drop-down list is for selecting the language/locale. For example, when "English" is selected, I want the link to be h ...

Having trouble with NextJS when trying to add an item to an element and render it in a Tailwind select

Struggling with displaying dynamic values in a select box using NextJS After fetching data from an API endpoint, I aim to populate a select box. However, my goal is to prepend a new element to the 'teams' array and ensure it appears first upon p ...

Is there a way for me to instruct jQuery to revert an element back to its initial value, prior to any dynamic alterations?

My question is regarding changing the content of a div using the `html()` method in JavaScript. I am currently working on implementing a "cancel" button and would like to revert the content back to its original value without having to completely reset it w ...

Guide on implementing a progress bar for file uploads with JavaScript and AJAX request

I am looking to implement a progress bar in my file uploader. Below is the ajax call I have set up for both file upload and progress tracking. $(function() { $('button[type=button]').click(function(e) { e.preventDefault(); ...

Bringing a JavaScript file into an Ionic/Angular 2 project

I have been attempting to integrate a simple JS library into Angular 2. The library in question is JIC.js. var jic = { /** * This function takes an Image Object (JPG or PNG) and returns a compressed new Image Object * @param {Ima ...