简体   繁体   中英

Callback and/or Promises javascript

It's been 2 days since I'm trying to understand my error. So far what I've learnt is that i will never be able to bypass "undefined" returned value because i cannot understand callback or promises... I rode all the poste, did some easy exemple, but I 'm not undertanding how to make it happen on my 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");
                        }
                    }

Please be gentle, I already hit my head so hard on others posts but it seems like I need more explanations...

async logic is a common place for newcommers to get tripped up on. But, it basically boils down to doing this:

Example of a synchronous code: (this is assuming that db.query() was written as a sync function, which its not)

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

Example of asynchronous code (which using db.query() as an async function)

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

The main difference here is that instead of doing return res you have to do callback(res) . This will always be the case when working with async code.

And its important to note that once you're in the async world, you can never go back to a sync world. ie This is impossible:

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

Once you're dealing with callbacks, you have to use callbacks everywhere . This is because the user of an async function has to itself be async. The only exception is if you don't care about what's getting returned or when, you just want it to go off and do some task.

So, this is how these principles applies to your specific chunk of code. This snippet of code is exactly the issue I was describing - you're trying to use an async function inside of sync logic.

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");

You'll have to convert this chunk of code to also be async, like this:

message.channel.send("You re openning " + args[2] + " boxes");
function callback(token_won) {
  realloot(token_won)
  if (token_won === "error number") {
    message.channel.send("Vous n'avez pas assez de box !");
  } else {
    message.channel.send("you won : " + token_won + " tokens !");
  }
}
lootbox_openning(callback, message.author.id, 1, args[2]);

(it's possible I didn't fully understand how you intended your original code to work, so take this example with a grain of salt. It shows the principle, but you'll have to tweak it to work for your needs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM