The function Promise.all is providing an array filled with undefined values and resolves prematurely before completing its task

I am encountering an issue with a function that is returning an Array filled with undefined values.

Below is the code segment in question:

classMethods.getQueries = function(models, dbId, dateStart, dateEnd) {
  return new Promise(function(resolve, reject) {
    // Retrieving database.
    .then(extractQueries, reject)
      .then(sortQueries, reject)
      .then(onlyTen, reject)
      .then(addText, reject)
      .then(function(queries) {
        console.log("getQueries completed", queries); // Array consisting of 10× undefined!
        resolve(queries);
      }, reject);

    // Additional functions go here.
  });
};

Everything runs smoothly until the addText function is called:

function addText(queries) {
  return Promise.all(queries.map(function(query) {
    models.queries.findById(query.queryId, {
      raw: true,
      attributes: [ "query" ]
    })
      .then(function(queryFetched) {
        query.text = queryFetched.query;
        console.log(query);
        
        return Promise.resolve(query);
      }, function(error) {
        return Promise.reject(error);
      });
  }));
};

This results in the following output:

"getQueries completed" [ undefined ×10 ]

10×
[query from database]
{ queryId: "…", text: "…" }

The reason behind the promise being returned before the loop completes is unclear to me.

Answer №1

Promise.all is used to resolve an array of Promise objects. If you're receiving an array of undefined, it may be because you forgot to return a Promise within your map callback:

function retrieveData(queries) {
  return Promise.all(queries.map(function(query) {
    // Ensure you include `return` here to avoid returning an array of `undefined`.
    return models.queries
      .findById(query.queryId, {
        raw: true,
        attributes: [ "query" ]
      })
      .then(function(queryResult) {
        query.text = queryResult.query;
        console.log(query);
        
        return Promise.resolve(query);
      }, function(error) {
        return Promise.reject(error);
      });
  }));
};

A simple value like undefined will be resolved immediately in Promise.all, leading to resolution before any other Promises are fulfilled in the callback.

Answer №2

Here is the resolution to my issue:

function retrieveText(queries) {
  return Promise.all(queries.map(function(query) {
    return new Promise(function(resolve, reject) {

      models.queries.findById(query.queryId, { raw: true, attributes: ['query'] })
      .then(function(retrievedQuery) {
         query.text = retrievedQuery.query;
         resolve(query);
      }, reject);

    });
  }));
};

Answer №3

Encountered a similar issue where my Promise.all(list) was returning an array of undefined values. I decided to solve it using the same method by incorporating a return statement in my function.

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

How can an Odata query be used to select expand properties with empty arrays?

I am a novice when it comes to OData querying and I could really use some direction. I am trying to utilize $filter to narrow down my search results, but I'm struggling with the syntax. My goal is to use OData to select table A, expand on navigation p ...

A guide on importing JSON files and rendering them in three.js

Greetings fellow developers! I have written some code to import a JSON file and render it using three.js. The JSON file was exported from the three.js editor. Strangely, there are no errors appearing in the console. window.onload = function() ...

Methods for extracting the result of a promise

Struggling with a project and in need of some assistance: Within a function, I have a promise and I am trying to figure out how to return the value of "current" so that I can utilize it elsewhere. My task involves retrieving data from Firebase, shuffling t ...

An unrecoverable error occurred: 'PDOException' was thrown due to an invalid parameter number in my array of parameters during execution

Encountering an error related to a specific line in my connect file: $statement->execute($params); Here is the content of my connect file (without credentials for security): <?php class connect { private static function db() { $pd ...

How can I make the type of a variable output be determined by an input that assigns a variable to a type within a function in Swift 5?

It was a bit confusing for me to use fread(), so I created a file reading struct with data, offsets, and reading methods. Now that it's working, I want to add a method to extract values from an n x m matrix and create a new matrix. (Similar to fread( ...

Encountering an endless loop when utilizing cycle-idb with a text field for user input

Struggling to develop a basic test app that captures user input from a text field, displays it, and stores it using cycle-idb. Unfortunately, I've been stuck in an endless loop no matter what steps I take. Below is the complete main function: functi ...

Why am I not seeing my views when trying to export them from a file in my routes folder?

I've been tinkering around with basic routing in ExpressJS and up to this point, I have implemented two routes: app.get('/', function(req,res) { res.render('index'); }); app.get('/pics', function(req,res) { res.rend ...

Retrieve the names of the files from the uploader class in the PHP script

After trying various methods without success, I'm getting frustrated. Currently in the process of familiarizing myself with PHP, so please be patient. I've been utilizing the class.uploader.php to upload files to my server. It functions correctl ...

Questions about setting up a controller in AngularJS

As I dive into my first AngularJS controller within a test application, I am encountering some challenges. I am retrieving a list of items from a RESTful web service and working on implementing basic CRUD logic for these items. The item list is displayed ...

Is the CSS Transition Solely Active for the Introductory Animation?

I'm currently looking to enhance the smoothness of div expansion and contraction on hover using CSS transitions. However, I have noticed that the Transition property only seems to affect the entry animation (i.e., when the mouse hovers and the div exp ...

I'm getting an error message that says THREE is not recognized. How can I resolve this issue

Currently, I am diving into the world of Three.js and encountering a persistent error that has been quite challenging to resolve. Despite my efforts in exploring various solutions, the error remains unresolved. I have ensured that the Three.js library is ...

Would you mind providing some clarification on these two JavaScript examples?

1: The result of foo && baz is not 1 because true equals to 1 in numerical terms. var foo = 1; var baz = 2; foo && baz; // returns 2, which is considered as true 2: In the expression console.log(foo + +bar);, the two plus signs have a ...

Disable default behavior in a SharePoint 2010 List new form with jQuery if conditions are not met

In the SharePoint 2010 List new form, there are 10 checkboxes available. I specifically need to choose exactly 3 of them and not less than that. Even though I implemented jquery for this purpose, it seems that the form does not stop submitting when the con ...

The Vue v-for directive encountered an unrecognized property during rendering

Trying to grasp the concept of v-for in Vue JS, especially since I am a newcomer to this framework. Since I am utilizing Django, custom delimiters are necessary. I have a script example that appends a list of objects to a data property: var app = new Vue( ...

The process of setting up React in the terminal becomes tricky when the VS code editor is directing to a non-existent path

Issue with VS Code editor not recognizing existing path Recently attempted to install React using the npx command in the terminal, following steps from various tutorials on YouTube. Despite trying all suggested methods, the installation didn't succee ...

Exploring how to utilize the map function in Next.js or React.js to retrieve data, specifically focusing on returning a JSON object and accessing its keys individually

I have successfully imported a JSON file using this code snippet: import Register from '@data/json/register.json'; The application then selects an object based on the URL parameters (e.g., 'http://localhost:3000/register/basketball' =& ...

How can you prevent the upload button from being clicked while a file is being uploaded and

By chance, I stumbled upon an issue that could potentially lead to a major problem with my application. I have developed an application where users can upload videos. Check out the Application here The main concern is that when a user uploads a video and ...

The location of the THREE.Group object is consistently set at the origin (0, 0, 0) and errors may arise when attempting to accurately determine its position

In my Three.js project, I am utilizing a THREE.Group to manage selected dominoes within the scene. However, I am facing an issue where the reported position of the THREE.Group remains constant at (0, 0, 0) despite adding or removing objects to it. Addition ...

Unable to reach the build on the Linux server

After deploying my react project on a Linux server and creating a production build using "sudo npm run build," I am encountering issues accessing the project. When I run the build file "serve -s build" and attempt to access the app via the remote URL provi ...

Challenges with AJAX in Web Browsing

I'm encountering some strange issues with AJAX functionality not working consistently across different web browsers. Is there a specific requirement or workaround to ensure smooth operation across all browsers? The initial problem I am facing is that ...