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

What could be causing the issue when the selected option is being changed and the condition does not work

Whenever the selection in a select element is changed, the corresponding text should also change. Check out this Fiddle here. (function($) { 'use strict'; function updateResultText() { var s1_is_1 = $("#s1").value === '1', ...

Is it possible to nest v-for directives within a component file?

Even after going through the VueJS tutorials multiple times, I am still unable to find a solution to this problem. My issue revolves around displaying a list of lists using accordions, which is supposed to work smoothly with vue-strap components. For exa ...

How to pass data/props to a dynamic page in NextJS?

Currently, I am facing a challenge in my NextJS project where I am struggling to pass data into dynamically generated pages. In this application, I fetch data from an Amazon S3 bucket and then map it. The fetching process works flawlessly, generating a se ...

Determine the total of all the values displayed in the footer of a jQuery

I am looking to show the total amount in the footer of a jquery datatable. Below is a snapshot of my datatable: https://i.stack.imgur.com/z01IL.png Here is the code snippet for my jquery datatable: for (var i = 0; i < length; i++ ) { var patient = ...

Instead of using a v-if condition, add a condition directly in the Vue attribute

Apologies for the unclear title, as I am unsure of what to name it with regards to my current issue, I am attempting to create a component layout using vuetify grid. I have a clear idea of how to do this conventionally, like so: <template> <v-fl ...

Create a function that will repeatedly call itself at specified intervals, increment a variable, and update the class values of elements with an id matching the current value of the

I'm attempting to create a setup that cycles through different images <div id="img_box" class="shadow" onload="imgCycle(1)";> <img id="1" class='opaque imgbox selected' src="media/img ...

What is the method for assigning a value to a variable in xhr.setRequestHeader?

I'm working on setting a value to the variable in xhr.setRequestHeader(Authentication, "Bearer" + parameter); with xmlhttprequest. Can you provide guidance on how to effectively pass a value to the variable within xhr.setRequestHeader? ...

Unable to authenticate with Firebase using ReactJS

I am currently working on developing a basic registration and login system using firebase authentication. However, I am facing an issue where the user appears to be saved when I restart the site in console.log, but the application redirects them back to th ...

Mastering the art of navigating through multiple nested objects is achievable by harnessing the power of recursive

I'm utilizing the AngularTree directive in my Angular application to display a tree view of a specific data structure. The data structure can be viewed at https://jsfiddle.net/eugene_goldberg/Lvwxx629/17/. You can find more information about the Angul ...

Why do variables maintain the same value across modules when using the require function in Node.js?

We have a scenario where we have multiple files in the same directory: data.js var anArray = [1,2]; module.exports = anArray; mod1.js var data = require('./data'); module.exports = data; mod2.js var data = require('./data'); modul ...

Steps to update the active state in the "reducer" when clicking on elements outside of the "reducer" area

Working with react-redux has presented some challenges for me. I've created multiple reducers such as action, root reducer, active_step reducer, and list_step reducer. One aspect that I find intriguing is the ability to dynamically map and change the ...

Utilizing ReactJS onBlur event for email field validation

Currently, I am using a MaterialUI Textfield for email input validation upon leaving the field. To achieve this, I have implemented a function triggered when the onBlur event occurs. My intention is to display an error message using helpertext. Here' ...

Unable to dynamically validate the input field for the name using Angular.js

Can someone assist me with an issue I'm having? I'm encountering an error while trying to dynamically validate input fields using Angular.js. Error: TypeError: Cannot read property '$invalid' of undefined Let me explain the code t ...

When the 'Show More' button is clicked, one Div will smoothly slide over another Div

I've been struggling for hours to find a way to make one DIV slide over another DIV below it instead of pushing it down. The setup is quite straightforward. I have a script that reveals more text when the 'Show More' button is clicked. Desp ...

React function does not provide a return value

In my function, I am calculating the current sum of elements. Within my Api, there is a method called Getcoin that works correctly when I log each element during the foreach cycle. However, I am not getting any results in the return statement or console.lo ...

Is there a way to retrieve all "a" tags with an "href" attribute that contains the term "youtube"?

My goal is to capture all a tags that have the href attribute containing the word youtube. This task requires the use of jquery. ...

I am facing an issue where both curl and file_get_contents are not functioning properly after

When attempting to access a user's city information using coordinates, I have encountered an issue with the response not being displayed in my console. The process involves a javascript function that takes latitude and longitude data, sends it to a PH ...

ESLint detecting error with returning values in async arrow functions

Currently facing a minor inconvenience instead of a major problem. Here is the code snippet causing the issue: export const getLoginSession = async (req: NextApiRequest): Promise<undefined | User> => { const token = getTokenCookie(req) if (!t ...

Certain hyperlinks are refusing to open within an embedded iframe

I'm currently facing an issue with finding a solution for a simple problem. I am in the process of developing a portfolio plugin and one of the requirements is to showcase projects within an iframe to demonstrate their responsive layout. However, I&ap ...

Tips for inserting an object into an array

Here's the data I received: { 0:{modifierId: 4, modifierName: 'Garlic', modifierPrice: 60 } 1:{modifierId: 1, modifierName: 'Tartar ', modifierPrice: 60} 2:{modifierId: 3, modifierName: 'Herb ', modifierPrice: 60} item ...