Employing a while loop within the context of a Promise

I am currently working on a user list and checking users with specific details. I'm utilizing sequelize js with express for this task. My query is whether it is possible to use a while loop in this manner to search and save data in the database. Any assistance would be greatly appreciated. Thanks in advance.

let royalty_bonus = async (sponsor) => {
    return await new Promise((resolve, reject) => {
        models.RoyaltyUser.findById(sponsor)
            .then(async (sponsorRow) => {
                let user_level = 1;
                let sponsor_id = sponsorRow;

                try {
                    while (sponsor_id != null && user_level <= 3) {
                        let level_length = await getLevel(sponsor_id.id, user_level);
                        if (user_level === 1 && level_length.length === 3) {
                            console.log('Level One Achieved By ', sponsor_id.id);
                        } else if (user_level === 2 && level_length.length === 9) {
                            console.log('Level Two Is Achieved By ', sponsor_id.id);
                        } else {
                            console.log('No Level');
                        }

                        await models.RoyaltyUser.findOne({where: {id: sponsor_id.sId}})
                            .then((sponsor_new_row) => {
                                sponsor_id = sponsor_new_row;
                            })
                            .catch((e) => {
                                console.log(' Inner Catch Error ', e.message);
                                reject();
                            });
                        user_level++;
                    }
                    resolve();
                }
                catch (e) {
                    reject(e);
                }

            })
            .catch((e) => {
                reject('catch ', e.message);
            });
    });

};
router.get('/royalty_user', async (req, res, next) => {
    royalty_bonus(4)
        .then(() => {
            console.log('done');
        })
        .catch((e) => {
            console.log('Catch two', e.message);
        })
});

Answer №1

Steer clear of the Promise constructor antipattern, refrain from using return await, and avoid mixing .then callbacks with the async/await syntax. Simplify your code like this:

async function royalty_bonus(sponsor) {
    const sponsorRow = await models.RoyaltyUser.findById(sponsor);
    let user_level = 1;
    let sponsor_id = sponsorRow;

    while (sponsor_id != null && user_level <= 3) {
        let level_length = await getLevel(sponsor_id.id, user_level);
        if (user_level === 1 && level_length.length === 3) {
            console.log('Level One Achieved By ', sponsor_id.id);
        } else if (user_level === 2 && level_length.length === 9) {
            console.log('Level Two Is Achieved By ', sponsor_id.id);
        } else {
            console.log('No Level');
        }

        const sponsor_new_row = await models.RoyaltyUser.findOne({where: {id: sponsor_id.sId}});
        sponsor_id = sponsor_new_row;
        user_level++;
    }    
}

router.get('/royalty_user', (req, res, next) => {
    royalty_bonus(4).then(() => {
        console.log('done');
    }, e => {
        console.log('Catch two', e.message);
    });
});

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

jQuery plugin for manipulating and adding days to dates

Within my Ruby on Rails application, there is a specific field where users can input a date. The current format for this date value is as follows: $('#search_form_handover_date').val() #returns "15-07-2014 09:00" I am looking to modify this dat ...

Participating in a scheduled Discord Voice chat session

Currently, I am in the process of developing a bot that is designed to automatically join a voice chat at midnight and play a specific song. I have experimented with the following code snippet: // To make use of the discord.js module const Discord = requ ...

Tips for styling Ajax.ActionLink elements with CSS

Hi there, I'm trying to style a navigation bar using CSS. I'm pulling the navigation bar values from a database using Ajax.ActionLink. I attempted to use JavaScript but encountered an error stating "jQuery is not defined", Here's the cod ...

Controller Function Utilizing Private Variable in AngularJS

After stumbling upon an Angularjs example online, I found myself perplexed. The code snippet in question is as follows: angular.module("testApp",[]).controller("testCtrl", function($scope){ var data = "Hello"; $scope.getData = function(){ ...

How can I achieve a similar functionality to array_unique() using jQuery?

When I select values from a dropdown, they are stored as an array like ["1","2","3"] Upon each change, the code below is executed to generate a new array based on the selected values: $('#event-courses-type').on('change', function(){ ...

Is your webpage slow to respond after a page-refresh? (Delayed HTML rendering causing lag)

Whenever I adjust the screen size to that of a phone or any device smaller than 768px, the search bar doesn't display in its proper position until the page is refreshed. It should be correctly placed right from the start. Furthermore, when I resize th ...

Efficiency in Javascript coding techniques

Hey there, I'm seeking some feedback on the efficiency of my aspect ratio function. This function is designed to determine the aspect ratio and limit the size of an image. Take a look and let me know what you think! function constrainTwoNumbers(optio ...

JavaScript code can be enhanced with HTML comments to improve readability

I have incorporated Google ad into my website using the following code. <script type="text/javascript"><!-- google_ad_client = "pub-"; /*Top 468x15 */ google_ad_slot = ""; google_ad_width = 468; google_ad_height = 15; //--> </script> < ...

One array comprises of all elements found in a separate array

After grappling with this problem for a while, I still haven't been able to find a solution. If I have 2 arrays structured like this: array1 = [ { name: 'John', age : 25}, { name: 'Jane', age : 58} ] array2 = [ { name: ...

Transform the size and convert an object from a picture into text based on the user's scrolling

I've been intrigued by the scrolling effects used on websites like Google SketchUp and Google Plus. It's fascinating how elements can transform as you scroll down the page. For example, on Google SketchUp's site, the banner starts off integr ...

The stubborn Node and Passport are refusing to update the password using user.setPassword

Currently, I am working on setting up my program to update a user's password only when the old one is confirmed as correct. Most of the code functions as expected except for one specific line: router.put("/:id/edit_password", isLoggedIn, isAdministra ...

Increase the thickness of the scrollbar track over the scrollbar thumb

I've come across several discussions on making the track thinner than the scrollbar thumb, but I'm looking to do the opposite. Is it possible to have a scrollbar track that is thicker than the scrollbar thumb? ...

Changing the data type of an integer to a string within an Object

I'm working with two arrays of objects. I need to convert the data values in the first format from integers to strings, but I'm struggling to find a simple solution. Is there anyone who can provide assistance? https://i.sstatic.net/mzqWE.png If ...

Insert newly added rows' values into the database dynamically

Hello there, I'm currently working on a PHP form that needs to dynamically add a table row when the "Add" button is pressed. I'm using a for loop to save the values, but I'm running into an issue where the data is not being saved into my dat ...

What steps can be taken to diagnose the cause of a failed Jquery AJAX request?

I am attempting to utilize the Yahoo Finance API to retrieve data in CSV format through Javascript. However, my current implementation shown below is not successful. $.ajax({ type: "GET", url: "http://finance.yahoo.com/d/quotes.csv?s=RHT+MSFT&f=sb2b3j ...

Can 2D canvas elements make use of CSS shaders?

Can CSS shaders, like "fragment" shaders, be utilized in 2D canvas contexts as well? ...

How can we map a promise that resolves to foo to a new promise that resolves to bar?

I am working on a function that uses an XMLHttpRequest to retrieve data and returns a promise with the response. But now I want to modify it so that the promise only contains a specific string from the response. Instead of resolving to response = {status ...

Ensuring the security of a password using express-validator

While using express-validator for express 3.x, I encountered a situation where users are required to enter their password twice when changing it or creating a new account. I am trying to figure out how to create a custom validator that can detect and repo ...

Implementing a peculiar timing mechanism with the integration of socket.io, jQuery Mobile, and the socket.emit() function

Currently in the process of working with cordova and node.js socket.io, I encountered a peculiar issue with socket.emit(); The following code fails to enter 'room', despite having correct coding: client-side jsfile.js //Two global variables fo ...

Issue: Input parameter should be either a single String consisting of 12 bytes or a string containing 24 hexadecimal characters

The occurrence of this error is related to the order in which the route/function is defined. Despite researching various reasons for this error, I have not found a solution specific to this issue. //Save Task router.get("/tasks/newrec",function(req,r ...