In JavaScript, promises remain in a pending state

How can I prevent my promises from remaining in the pending state and resolve them instead?

    var foundPeopleA = findPeopleA().then(function(result) {
        var res = []
        result.map(function(el) {
            res.push(getProfileXML(el.sid));
        });
        return res
    });

    var foundPeopleB = findPeopleB().then(function(result) {
        var res = []
        result.map(function(el) {
            res.push(getProfileXML(el.sid));
        });
        return res
    })

    return Promise.all([findPeopleA, findPeopleB]).then(function(results) {
        console.log(results) //[ [ Promise { <pending> }, Promise { <pending> } ],  [ Promise { <pending> }, Promise { <pending> } ] ]
    })

However, by changing the body of the two functions above to

        var res
        result.map(function(el) {
            res = getProfileXML(el.sid);
        });
        return res

the promises will not remain in a pending state and the results will be returned.

Answer №1

Unlike promises, arrays do not behave the same way when returned. If you return an array of promises, the method then will also return an array of promises. The execution process differs in case a non-promise value is returned. It's important to note that only by returning a promise will it get executed before proceeding to the then function. In this specific scenario with foundPeopleA and foundPeopleB, both construct separate arrays of promises which require concatenation prior to passing them into Promise.all or similar methods for proper execution.

Answer №2

The issue arises when you try to resolve promises individually using then, whereas all is designed to handle multiple promises by providing it with an array of unresolved promises. By doing this, a new promise is created that combines the results of all the promises together. To fix this problem, simply use:

Promise.all([fetchDataA(), fetchDataB()])
.then(function(results) ...

Answer №3

One way to handle your array is by assigning it to the result of mapping.

var foundPeopleA = findPeopleA().then(function(result) {
    var res = []
    res = result.map(function(el) {
        return getProfileXML(el.sid);
    });
    return res
});

Alternatively, you could consider resolving the promise.

var foundPeopleA = findPeopleA().then(function(result) {
    var res = []
    res = result.map(function(el) {
        return getProfileXML(el.sid);
    });
    resolve(res);
});

In any case, it seems crucial to construct your array by returning values from the mapping for creating the new array.

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

Calculating the Bounding Box of SVG Group Elements

Today I encountered a puzzling scenario involving bounding box calculations, and it seems that I have yet to fully understand the situation. To clarify, a bounding box is described as the smallest box in which an untransformed element can fit within. I h ...

The ngAfterContentInit lifecycle hook is not triggered when the parent component updates the child component

I am trying to understand the functionality of the ngOnChanges callback in Angular. I have implemented it to observe changes in a property annotated with the Input decorator as shown below: @Input() postsToAddToList: Post[] = []; However, after compiling ...

Optimal method for identifying all inputs resembling text

I'm in the process of implementing keyboard shortcuts on a webpage, but I seem to be encountering a persistent bug. It is essential that keyboard shortcuts do not get activated while the user is typing in a text-like input field. The approach for hand ...

Troubleshooting JavaScript's onchange Function Dysfunction

Here is the code snippet I am working with: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> <script src="jquery-2.2.1.min.js"></script> <script src="slike.js"></script> ...

Adding a fresh element and removing the initial item from a collection of Objects in JavaScript

I'm working on creating an array of objects that always has a length of five. I want to push five objects initially, and once the array reaches a length of five, I need to pop the first object and push a new object onto the same array. This process sh ...

The specified selector is invalid or illegal in HTMLUnit

Attempting to mimic a login using htmlunit has presented me with an issue despite following examples. The console messages I have gathered are as follows: runtimeError: message=[An invalid or illegal selector was specified (selector: '*,:x' erro ...

Angular JS: Distribute objects from a single array to various arrays or services

I have recently embarked on developing a basic app using Angular JS, utilizing a service/factory to manage data and enable the addition of objects. Within the array of various individuals (listed in the html), you can include them as candidates by employi ...

Why are my basic style properties not appearing correctly when I use json_encode on an array?

My calendar is written in Javascript within a table with the ID "calendario," allowing me to manipulate it using calendario.rows[i].cells[i]. This calendar lets users make reservations and provides an option to close a day if there are too many reservatio ...

Eliminate repeated elements by comparing two sets of data

I have two arrays of data, rlT and refundT. My goal is to eliminate any duplicate items from the rlT array that have a matching transactionId in the refundT array. I came across a solution using filter() and find() on Stack Overflow: Remove all elements co ...

Look into the data with vue.js, but there's not much

1. As a newcomer to vue.js, I encountered some surprising issues while experimenting with examples. The first one arose when I assigned an id to the body tag and included the following JavaScript code: <html> <head> <meta charset="utf-8 ...

Limiting jQuery searches to a specific region: Tips and tricks

If I have the code snippet below: <div class="foo"> <div> some text <div class="bar"> </div> </div> </div> <div class="foo"> <div> some text <div class="bar"> some text </div> </div> </ ...

Following the submission of a message, the textarea automatically inserts a line-break

Can someone please help me troubleshoot an issue with my chat app? Every time I try to send a message, the textarea adds a line break instead of just focusing on the textarea so I can send a new message smoothly. I have recorded a video demonstrating the ...

The equivalent of e.preventDefault() in Java (for Android) is to replace the typed text

I am working on a jQuery/JavaScript function that will replace any text typed in an input field with a specific text. Here is the code snippet: $('input').on('keydown', function(e){ e.preventDefault(); count++; if (count == ...

Connecting Vue component data to external state sources

I am facing a challenge with integrating a Vue component into a large legacy system that is not based on Vue. This component retrieves data through AJAX requests and displays information based on an array of database record IDs, typically passed at page lo ...

Tips for including a JSON file within the utils directory of a Node.js project

I have a JavaScript file located in the utils folder of my Node.js project. This JS file is responsible for retrieving data from a database. However, at the moment, I only have mock data stored in a local JSON file. Now, I need to figure out how to load th ...

What are the steps to save data on a user's computer through a web browser?

Is it feasible to save data in the client's computer using a web browser and jQuery code to interact with the file system? ...

Add an image to a div element and determine its height, then apply the height to the CSS property

Here is my JavaScript code that utilizes jQuery: $(".article_big_photo").click(function() { $('#screen').css({ opacity: 0.5, 'width':$(document).width(),'height':$(document).height()}); $('#screen').show() ...

Using AngularJS to send data from a controller to a factory

Looking to implement a basic pagination feature with data from the backend. Each page should display 10 activities. /feed/1 -> displays 0-10 /feed/2 -> displays 10-20 /feed/3 -> displays 20-30 The goal is to start at page 1 and increment the pag ...

Utilizing Phantom Js with Apache server

After creating a JavaScript app, I realized the importance of making it SEO friendly. I am curious if anyone has experience setting up a crawlable webpage on Apache using Backbone.js (potentially with assistance from PHP and .htaccess files, or with Phant ...

Loading dynamic images in HTML using Javascript and Django templates

Attempting to load a specific image using javascript within a django template has presented challenges due to the formatting of django tags. The standard django static asset source in an img tag looks like this: {% load static %} <img src="{% static & ...