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

When setting an empty URL with Fabricjs' setBackgroundImage function, a null reference error occurs in the _setWidthHeight

Recently, I stumbled upon an article detailing a method to clear the background of a fabric canvas... canvas.setBackgroundImage('', canvas.renderAll.bind(canvas)); In the development of my online design tool which utilizes Fabricjs 1.4.4, I have ...

When using jQuery to parse JSON, I am unable to make changes to an array

inventory = new Array(); $.getJSON('items.php', function(data){ $.each(data , function(i,jsonData) { inventory[1] = "item"; }); }); alert(inventory[1]); This code is supposed to display the items in the inventory, but it's ...

Employing the html.validationmessagefor to display a client-side error notification

My text fields have server-side validation messages. The field 'title' is a required field on the server side with a '[Required]' data attribute in the class, but it only seems to be checked on a postback or form submit. I am saving the ...

Transferring PHP array to JavaScript with the help of AJAX

I've been working on integrating Google Maps and Instagram in a project of mine. My main challenge is figuring out how to pass the coordinates of Instagram photos from my PHP file to my JavaScript file using AJAX. I'm quite lost when it comes to ...

Tips for dynamically populating an HTML table with data from a JSON array using JQuery

I have generated an HTML table <table id="top_five_table"> <tr> <td> </th> <th>URL</th> <th width="90">Total Hits</th> <th width="380">Percentage of all Hits</th> </tr> <tr> ...

Using React to implement MUI autocomplete feature alongside a MUI form

Recently, I have been utilizing a MUI form structured in the following manner: <Box component="form" onSubmit={event => { return handleSubmit(event); }} noValidate sx={{mt: 1}}> <TextField margin="normal" ...

Updating and eliminating text within an array of objects using Vue JS

My Axios request pulls in an array of objects named 'uniquecolors'. Here is what it looks like: mycolors color: [GREEN, RED, BLUE, YELLOW, ORANGE,ORANGE,GREEN,] color: [GREEN, RED, BLUE, YELLOW, ORANGE,ORANGE,GREEN,] color ...

communicating global variables between Django and JavaScript

I want to make variables from my settings.py accessible in all JavaScript code used throughout my project. What is the best way to accomplish this elegantly? Currently, I am considering two options: Create a context processor and define these globals ...

Preserve the location of a moveable div using jQuery

I have implemented draggable divs in my JSP page, allowing users to move them around freely. After dragging the divs, I would like to save their positions either in a cookie or database for future reference. Could you please advise on the best way to ach ...

Troubleshooting the issue with reactdom.render() functionality in CodeSandbox

Having issues with ReactDom in CodeSandbox for React. The HTML file includes: <body> <div id="root"></div> </body> <script src="scr/index.js"> The JavaScript file (named index) includes: ReactDOM.rende ...

The jQuery keyup event initiates multiple times, increasing exponentially with each trigger

I recently added a search bar with auto-complete functionality to my website. The search bar queries the database for elements that begin with the text entered by the user as they type. Although it works well, I noticed that every time the user inputs ano ...

Verify in Mongo if a specific document is already present

Currently in development of my MEAN app, the client-side sends a $http POST request to my API with a JSON array containing soundcloud track data specific to each user. My goal now is to save these tracks to my app database within a 'tracks' table ...

How to disable the ripple effect of a parent button in Material UI when clicking on a nested child button?

Attempting to nest one button within another (IconButton inside ListItem with the button prop) is proving challenging. The issue lies in the fact that the ripple animation of the ListItem is triggered even when clicking on the IconButton. Ideally, I would ...

What is the method for extracting a list of properties from an array of objects, excluding any items that contain a particular value?

I have an array of objects, and I want to retrieve a list with a specific property from those objects. However, the values in the list should only include objects that have another property set to a certain value. To clarify, consider the following example ...

trigger a p:ajax event by employing a right-click action

Currently, I am utilizing JSF and Primefaces 5.2. A peculiar observation I made is that when a commandLink is used with the onclick event and p:ajax, it creates a selection effect. <h:commandLink id="commandLink"> <p:ajax event="click"/> </ ...

What is the reason Angular is unable to locate a controller for a directive in an external file?

As a newcomer to Angular, I'm struggling to comprehend John Papa's recommendations. His guidelines suggest placing controller logic inside directives, but this approach doesn't seem intuitive to me. Despite my efforts to implement it myself, ...

Bind AngularJS data to select elements

I am encountering an issue with data binding on a select tag, despite following the guidelines in the documentation. Here is my select element: <select id="start-type" ng-model="startType"> <option value="day-of-week">Day of the week</op ...

Leveraging 2-dimensional indexes in collaboration with the $geoNear operator

I encountered an issue while attempting to use geoNear with aggregate as I received the following error message: errmsg: "'near' field must be point" The reason for this error is because my location field is represented as [Number]: var locati ...

A comprehensive guide on harnessing the power of server-sent events in express.js

After incorporating the express.js framework, I configured my REST server. Now, I am interested in integrating server-sent events (sse) into this server. However, upon implementing the sse package from npmjs.com, an error occurs. It seems that the error is ...

A guide on extracting data from an HTML table containing various input fields

I have a webpage with this table generated by a PHP script. What I need to do is extract the values from each of the 4 input fields and save them in separate JavaScript variables. Each button already has an onclick="fetchGrades(); trigger added. How can ...