JavaScript Callbacks and Promises: Exploring Asynchronous Programming

For the past 2 days, I've been struggling to figure out my mistake. It seems that I can't get past the "undefined" returned value because I'm having trouble grasping callbacks or promises. Despite reading numerous posts and trying simple examples, I just can't seem to apply it to my own code...

function realloot(data){
    return data;
    console.log(`${data}`);
    }
 
 
function lootbox_openning(callback, user, type, nombre){
 
let sqlQueryopenbox = `SELECT item_qty FROM users_items WHERE discord_id = '${user}' AND item_id = ${type};`
 
let token_won=0;
let real_token_won=0;
let common_pp_looted = 0;
let rare_pp_looted = 0;
let epic_pp_looted = 0;
 
        db.query(sqlQueryopenbox, (err, rows) => {
            
            let user_box_real_qty = rows[0].item_qty;
            let sql;
        
            if (err) {
                real_token_won="sql error";
                throw err;
                }
                
            if (nombre > user_box_real_qty){real_token_won="error number";}
            
            else {
                //function open
                
                if (type==1) { 
                
                    for (var i = 0; i <= nombre; i++){
                        token_won=little_box_open();
                        real_token_won=real_token_won+token_won;
                    }
                    var myreturn = callback(real_token_won);
                    console.log(`${myreturn}`);
                    return myreturn;
                }
                if (type==2) {}
                if (type==3) {}
            }
        
        });
 
}
 
 
//this is a bot discord so huge on.message here...
 
 
 
            case "open":
                if (!args[1]) return message.channel.send('please give value box | bigbox');
                
                if (args[1] ==='box' ){
                    if (!args[2]) {message.channel.send ("Specify number please");}
                    if (args[2]) {
                        var number = parseInt(args[2]);
                        if (Number.isInteger(number)){
                            message.channel.send ("You re openning "+args[2]+" boxes");
                            **var token_won = lootbox_openning(realloot, message.author.id, 1, args[2]);** //PROBLEM IS HERE 
                            if (token_won==="error number"){message.channel.send ("Vous n'avez pas assez de box !");}
                            else {message.channel.send ("you won : "+token_won+" tokens !");}
                            }
                        else message.channel.send ("Give a valid number");
                        }
                    }

I've hit a wall with this problem and despite all my efforts, I still need more clarity and explanations...

Answer №1

Understanding asynchronous logic can be challenging for newcomers, but it essentially comes down to this:

Let's look at the difference between synchronous and asynchronous code:

function doQuery(id) {
  let res = db.query(`SELECT * FROM table WHERE id=${id}`)
  return res
}

With asynchronous code:

function doQuery(id, callback) {
  db.query(`SELECT * FROM table WHERE id=${id}`, function(res) {
    callback(res)
  })
}

The key difference is that instead of using return res, you need to use callback(res). This pattern is essential when dealing with asynchronous operations.

Once you venture into the world of async programming, there's no turning back to synchronous methods. For instance, attempting to mix sync and async logic like this is not feasible:

// some sync logic
let resultOfAsyncOperation = someAsyncFunction()
// some sync logic

When working with callbacks, everything needs to follow an async flow. The only exception is if you simply want a task to be executed without worrying about the timing or return value.

Applying these principles to your specific code snippet reveals a common issue - mixing async functions in synchronous logic.

var number = parseInt(args[2]);
if (Number.isInteger(number)) {
    message.channel.send("You're opening " + args[2] + " boxes"); **
    var token_won = lootbox_opening(realloot, message.author.id, 1, args[2]); ** //PROBLEM OCCURS HERE 
    if (token_won === "error number") {
        message.channel.send("Not enough boxes!");
    } else {
        message.channel.send("you won: " + token_won + " tokens!");
    }
} else message.channel.send("Provide a valid number");

To resolve this issue, you'll also need to convert this portion of code to be asynchronous:

message.channel.send("You're opening " + args[2] + " boxes");
function callback(token_won) {
  realloot(token_won)
  if (token_won === "error number") {
    message.channel.send("Not enough boxes!");
  } else {
    message.channel.send("you won: " + token_won + " tokens!");
  }
}
lootbox_opening(callback, message.author.id, 1, args[2]);

(Keep in mind that this example may need adjustments based on your specific requirements, but it illustrates the concept of transitioning to async practices)

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

Is it possible to customize the query result in Oracle Database using an alias to meet specific business requirements?

When working with Oracle database, it's important to note that it is case insensitive. This means that even if you use an alias in lowercase, the column name will always be displayed in uppercase. For example, if you execute the following query: Selec ...

Is it possible to utilize an npm package in TypeScript without a d.ts definition file?

Is it possible to use an npm package in TypeScript and Node.js without a .d.ts definition file? If so, how can I make it work? Currently, my code looks like this and I'm getting an error that says "cannot find module 'node-rest-client'" bec ...

Establish the condition if the array is present

I am looking to conditionally set a state based on the existence of data retrieved from the server. const [names, setNames] = useState([...details?.names]) The details object is passed in as props and fetched from the database. The array details.names com ...

Using JS/AJAX to update a section of a webpage when a button is clicked

Currently, I am working on developing a generator that will display a random line from a .txt file. Everything is going smoothly so far, but I have encountered an issue - I need a specific part of the page to refresh and display a new random line when a ...

The Javascript function will keep on executing long after it has been invoked

I am currently facing an issue with calling a JavaScript function within an AJAX call. The progress function below is supposed to be executed every time the for loop runs. However, the problem is that although progress is being run as many times as the for ...

Is it possible to transfer a specific feature from jQuery to Prototype?

I find myself in a situation where I have to use Prototype instead of jQuery, even though I'm not as familiar with it. Can anyone assist me in transforming the following script: var output={}; $$('ul li').each(function(item){ var firstL ...

When using Vue2, pushing a string to an array simply replaces the existing string instead of appending it

My current task involves manipulating a local data array by adding and removing strings within a method. However, I have noticed that my logic always results in the array containing only a single string passed to the updateIdArr method. Even after removin ...

Take the user input from the form and incorporate it into the URL for the AJAX request

How can I dynamically update the URL in the AJAX call asynchronously? I've made a few attempts, but none of them seem to work. This is the current code: <!-- Input form --> <form class="navbar-form navbar-left" role="search" id="formversion" ...

Is it possible for Javascript to handle a string of 27601 characters in length?

I have created a webmethod that returns an object containing strings. Each string in the object is of length 27601. This pattern continues for all array members - str(0) to str(n). When my webmethod returns this exact object, I encounter an issue on the c ...

The issue with ng-repeat causing incorrect image width in Flexslider

My webpage features image scrolling functionality, powered by Flexslider. The images on the page are sorted by date - for example, selecting "last 7 days" will display images from the past week (data managed through AngularJS). However, when the JSON dat ...

I am having issues with the accuracy of my JavaScript number validation function

function CheckIfNumeric() { var quantity = jQuery("#txtShippedQuantity").val(); quantity = quantity.toString(); for (i = 0; i < quantity.length; i++) { var character = quantity.charAt(i); if (isNaN(character)) { ...

The issue arising from Firefox's handling of try/catch blocks in window.onerror is not adequately addressed

It appears that Firefox handles errors differently when they occur in the window.onerror event handler compared to other browsers. While IE, Chrome, and Safari behave as expected, Firefox seems to treat any error in this context as a critical exception, ev ...

The OnsenUi getCurrentPage() function returns an empty object

As I work on creating a hybrid mobile app using Onsen UI, I've encountered an issue regarding navigation and data transfer between two pages. My starting point is index.html, which consists of a main.html ons-template along with ons-navigation and ons ...

The initial Ajax request returned an empty data string, but upon retrying, the correct data

Let's address the current situation Previously, I had a free domain that was unexpectedly closed by the web admins without any explanation. Everything functioned perfectly on that domain, but after opening a new one on a different site, I started enc ...

Is there a way to extract video frames from a WebRTC local stream and transfer them to Python?

I am in the process of developing a video call application similar to Google Meet or Zoom, incorporating object detection using Python Flask or Django. Here is how the application functions: Users can join a channel for the video call The camera ini ...

Ensure that all items retrieved from the mongoDB query have been fully processed before proceeding further

In the midst of a challenging project that involves processing numerous mongoDB queries to display data, I encountered an issue where not all data was showing immediately upon page load when dealing with large datasets. To temporarily resolve this, I imple ...

Testing Equality in Unit Tests: Comparing Objects and Arrays

Forgive me for this seemingly silly question, but I'm having trouble understanding it. I am a newcomer to both testing and JavaScript, so please bear with me. Here is the test in question: describe('initialized from copy job functionality&apos ...

What is the best way to delete a particular CSS class using jquery?

My task is to remove the "btn" class from items that have an additional argument in their class name, such as: <input type="button" class="btn btn-mini btn-success email-user" id="emailid5" value="Email Tester"> I specifically need to only remove t ...

Why Changing the Width of a Flexbox Container Doesn't Impact Its Children?

Attempting to use TweenLite to animate the width of the blue sidebar down to zero, however facing an issue where the content breaks outside the parent's bounds. https://i.stack.imgur.com/4rEVr.png It is unusual for this to happen with Flexbox, given ...

Tips for retrieving only the changes or updates from DynamoDB streams

Currently, I am faced with a scenario where I must comprehend the distinction between NEW_IMAGE and OLD_IMAGE on dynamoDB streams. As per the information available at: https://aws.amazon.com/blogs/database/dynamodb-streams-use-cases-and-design-patterns/ ...