Tips for ensuring that an API waits for a loop to complete when searching for an array of IDs in SailsJs

When querying a table in my database using the find() method, I am returned with a record that includes a column containing an array of user IDs.

My goal is to iterate through these IDs and use another find() method to retrieve the details of each user.

Based on my understanding, I believe I need to implement a promise to ensure that the loop completes before proceeding. However, I am unsure of how to correctly integrate a promise in this scenario.

Despite attempting the following code, both console logs are showing empty arrays:


getShortList: (req, res) => {

    function shortList(ids) {
        var companies = []

        for (var i = 0; i < ids.length; i++) {
            await new Promise(resolve => {
                setTimeout(() => {
                    Company.find({ id: ids[i] }).exec((err, company) => {
                        if (err) return res.serverError(err)
                        
                        companies.push(company)
                    })
                }, 5000)
                resolve(companies)

            })

        }
    }

    async function testFunc() {

        var job_type = req.body.job_type
        var job_listing_id = req.body.job_listing_id

        Supplier_job_listing.find({ id: job_listing_id }).exec((err, job) => {
            if (err) return res.serverError(err)

            var list = shortList(job[0].shortlisted_bidders_ids)
            list.then((result) => {
                console.log('receiving it here', result)
            })


        })

    }
    testFunc();

}

Answer №1

Without seeing your full code, the solution to your issue may look something like this:

async function fetchList(items){
  let promises = [];
  for (let i = 0; i<items.length; i++){
    promises.push(Database.find({item: items[i]}));
  }
  let data = await Promise.all( promises);
  return data;
}

function processData(){
  fetchList()
   .then((data) => {
     // manipulate retrieved data
   })
   .catch(error){
     // console.log(error);
   }
}
processData();

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

An animation triggered by scrolling using the @keyframes rule

Is it possible to smoothly animate a variable font using @keyframes on scroll and have it complete the animation loop when the user stops scrolling, rather than snapping back to the starting position? I've managed to make the animation work, but it l ...

"Encountering an undefined error when making an AngularJS $http post request and receiving a

I am working on retrieving a specific value from the server side by passing a variable from the front-end (AngularJS javascript) to the backend (PHP) using $http. Once the server side (PHP) receives the value from the front-end, it executes an SQL query to ...

Javascript unable to update the DOM

I've been working on a project to prototype a simple functionality using JavaScript for learning purposes. However, I've encountered an issue where the contents within the <p> tag are not updating, and I'm currently stuck. Here's ...

Angular HTTP client implementation with retry logic using alternative access token

Dealing with access tokens and refresh tokens for multiple APIs can be tricky. The challenge arises when an access token expires and needs to be updated without disrupting the functionality of the application. The current solution involves manually updati ...

Executing functions in real-time using React Native

I'm fairly new to Object-Oriented Programming (OOP) and my understanding of promises, asynchronous/synchronous function execution is quite basic. Any guidance or help from your end would be greatly appreciated! Let's take a look at an example fr ...

Guide on designing a navigation list with unique buttons that alter the displayed content based on the selected button

As a newcomer to the world of programming, I have a basic inquiry that I hope you can assist me with. I have successfully created a navigation list, but I am struggling to make it functional. For instance, if my navlist consists of 3 buttons: Home, About, ...

Establish the directory for javascript and css files following the designated URL rewriting regulations in the .htaccess file

Currently in the process of rewriting my URLs by configuring rules in the .htaccess file. The current version of my .htaccess file looks like this: Options +FollowSymlinks RewriteEngine on AddType text/css .css RewriteRule ^lunettes-collection/([ ...

Utilize a shorthand label for a column within the WHERE clause

I wrote a query in Postgres SQL with a column alias and it's working correctly: select email as e from users The query displays the results under the e column alias. However, when I try to use the where condition with e, I encounter an error: selec ...

Can a resolution be found for this authentication (login) issue?

I encountered this issue only when providing a incorrect email that is not in the database: Notice: Trying to access property 'email' of non-object in C:\path\UsersCOntroller.php on line 10 However, everything works fine when the pas ...

Tips for transforming numerical date data into a string format

Is there a method to convert the numeric month in a table into a string format? <table style="width: 100%;"> <tr> <th>Date</th> <th>Total</th> </tr> <tr> <td id="date ...

Does Peerjs exclusively cater to one-on-one webrtc communication?

Can PeerJS be used to implement one-to-many audio communication with WebRTC? I'm currently using Socket.io with Node.js. Is this sufficient for WebRTC integration? As a beginner in WebRTC, could you recommend some options for implementin ...

Execute an INSERT INTO statement with a query, incorporating a default value

My challenge is running an INSERT INTO table SELECT... FROM... statement. The issue is that the destination table has 5 columns, while the source table only has 4 columns. I need to set a default value for the missing 5th column during the insertion proc ...

The jQuery function fails to execute when the script source is included in the head of the document

I'm relatively new to working with scripts and sources, assuming I could easily add them to the header and then include multiple scripts or functions afterwards. Everything seemed to be working fine at first, but now I've encountered a problem th ...

Retrieve all attributes of an element with the help of jQuery

I am attempting to extract all the attributes of an element and display their names and values. For instance, an img tag may have multiple unknown attributes that I need to access. My initial idea is as follows: $(this).attr().each(function(index, element ...

Facing issues with receiving API response through Postman encountering error { }

In my MongoDB database, I have created documents for Families, Users, and Devices (https://i.stack.imgur.com/oeDU0.png). My goal is to retrieve all devices associated with a specific family using the family's Id provided in the HTTP request. For examp ...

Service in AngularJS designed specifically for storing and managing SEO metadata

I stumbled upon a tutorial that introduced me to using a service for dynamic SEO metadata here: However, I encountered an issue - It seems like the service is not accessible outside of the controller's view. <div ui-view></div> Here is t ...

Having issues with ng-repeat not displaying any content

Let me describe the current situation I am facing: app.controller('ResourceController', function($scope, $sce){ var resourceData; $scope.data = ''; $scope.loadResources = function(){ $.get('con ...

Is there a way to automatically restart my Gulp task when I save changes?

I have a series of Gulp tasks in version 4 that handle tasks like compiling Webpack and Sass, optimizing images, etc. These tasks are automated through a "watch" task while I am working on a project. However, when my watch task is active, saving a file tr ...

JavaScript - Matching overlapping time intervals

Struggling to develop a custom filter using Javascript, I aim to determine if two time ranges in millisecond getTime() format match. The first time range is retrieved from an object while the second comes from user input for filtering. Currently, my code c ...

How can you match the width of a series of elements to the width of an image directly preceding the div?

Looking to ensure that a series of captions have the same width as the images preceding them. This is the HTML code: <div class="theparent"> <img src="pic.jpg"/> <div class="caption"> hello </div> <div> <div ...