简体   繁体   English

等待回调函数,然后再返回另一个回调函数的结果

[英]Wait for callback function before the result of another callback function

I have a problem in my method. 我的方法有问题。 elenco_prodotti must wait the method sincro.query to proceed to add the final outputs, but now I see only the empty divs, because it needs to be synchronous. elenco_prodotti必须等待方法sincro.query继续添加最终输出,但是现在我只能看到空的div,因为它需要同步。

Please, help me! 请帮我!

this.elenco_prodotti = function (callBack) {
    var output = '';

    for (var c = 1; c < 5; c++ /*categoria*/)
    {
        for (var p = 1; p < 5; p++/*pagina*/)
        {
            output += "<div class='pag_" + p + " cat_" + c + "'>";

            var sql = 'SELECT cat_varianti,colore_tasto,id,descrizione,prezzo_1 FROM prodotti WHERE categoria="' + c + '" AND pagina="' + p + '"';

            output += '<div class="bs-docs-section btn_' + comanda.dispositivo + ' "> \n\
            <div class="bs-glyphicons"> \n\
             <ul class="bs-glyphicons-list">';

            for (var y = 1; y <= 6; y++) {
                for (var x = 1; x <= 8; x++) {

                    var posizione_attuale = y + "-" + x;
                    var testo_query = sql + ' AND posizione="' + posizione_attuale + '" LIMIT 1;';

                    comanda.sincro.query(testo_query, function (prodotto)
                    {
                        if (prodotto[0] && prodotto[0]['descrizione'].length > 0)
                        {
                            prodotto = prodotto[0];
                            prodotto['descrizione'] = prodotto['descrizione'].replace("'", " ");

                            switch (comanda.dispositivo) {
                                case "COMANDA":
                                    if (prodotto['descrizione']) {
                                        output += '<li style="background-color:' + prodotto['colore_tasto'] + '" onClick="aggiungi_articolo(\'' + prodotto['id'] + '\',\'' + prodotto['descrizione'] + '\',\'' + prodotto['prezzo_1'] + '&euro;\',\'null\',$(\'#quantita_articolo\').val(),\'null\',\'' + prodotto['cat_varianti'] + '\')"> \n\
                                                        <span  class="glyphicon-class">' + prodotto['descrizione'] + '<br/>€ ' + prodotto['prezzo_1'] + '</span> \n\
                                                            </li>';
                                    } else {
                                        output += '<li style="display:table;"> \n\
                                                         <span class="glyphicon" aria-hidden="true"></span> \n\
                                                                <span  class="glyphicon-class"></span> \n\
                                                                    </li>';
                                    }
                                    break;

                                case "LAYOUT TASTI":
                                    output += '<li ';

                                    if (prodotto['colore_tasto']) {
                                        output += 'style="background-color:' + prodotto['colore_tasto'] + '"';
                                    }
                                    output += ' onClick="modifica_articolo(\'' + c + '\',\'' + posizione_attuale + '\',\'' + prodotto['colore_tasto'] + '\');">  \n\
                                                    <span  class="glyphicon-class">' + prodotto['descrizione'] + '</span> \n\
                                                        </li>';

                                    break;

                                default:
                                    break;
                            }
                            output += '</ul></div></div>';
                        }
                        else
                        {
                            prodotto = null;
                        }
                    });
                }
            }
            output += '</div>';
        }
    }
    callBack(output);
};

You need to wait for multiple asynchronous things to happen. 您需要等待多个异步事件发生。

At the moment, your code will not work because you are capturing loop variables in a callback function that probably completes after the loops have completed, meaning that you will have unreliable values for c , p , x , y . 目前,您的代码无法使用,因为您正在捕获一个可能在循环完成后完成的回调函数中的循环变量 ,这意味着您将无法获得cpxy可靠值。

You could use Promises to get around this: 您可以使用Promises来解决此问题:

this.elenco_prodotti = function (callBack) {
    var promises=[];
    for (var c = 1; c < 5; c++ /*categoria*/)
    {
        for (var p = 1; p < 5; p++/*pagina*/)
        {
            var sql = //your sql;
            for (var y = 1; y <= 6; y++) {
                for (var x = 1; x <= 8; x++) {

                    var posizione_attuale = y + "-" + x;
                    var testo_query = //more sql;
                    var prom=new Promise(function(resolve,reject)){
                        var loopVars = {c:c,p:p,y:y,x:x};
                        comanda.sincro.query(testo_query, function (prodotto)
                        {
                            resolve({loopVars:loopVars,prodotto:prodotto})
                        });
                        promises.push(prom);
                    }
                }
            }
        }
    }
    Promise.all(promises).then(function(data){
        //this callback executes only when
        //all promises have completed...
        var output="";
        data.forEach(function(){item}{
            var c=item.loopVars.c;
            var p=item.loopVars.p;
            var x=item.loopVars.x;
            var y= item.loopVars.y;
            var prodotto=item.prodotto;
            //build your output string here
        });
        callBack(output);
    });
};

Ok, this is good for one query, but i have this? 好的,这对于一个查询是好的,但是我有这个吗?

It doesn't work... I'm not undestanding very good. 它行不通...我不是很好。

var FunzioniDB = function () {

this.elenco_prodotti = function (callBack) {
    //$time=microtime(true);

    var output = '';
    var promises = [];

    var promessa = new Promise(function (resolve, reject) {

        //query per vedere tutti gli id di categoria
        comanda.sincro.query('SELECT id FROM categorie WHERE 1 ORDER BY id ASC', function (cat) {
            //console.log(cat.length);

            for (var key in cat) {
                //console.log(cat[key].id);
                //query per vedere l'ultimo numero di pagina
                comanda.sincro.query("SELECT pagina FROM prodotti WHERE pagina NOT NULL AND pagina != '' AND categoria='" + cat[key].id + "' ORDER BY pagina DESC LIMIT 1;", function (pag) {
                    output += "<div class='pag_" + i + " cat_" + cat[key].id + "' style='display:none;'>";
                    //console.log("cat1 - pagine:= " + parseInt(pag[0].pagina));
                    //apre le intestazioni della comanda 
                    //

                    for (var i = 1; i <= (parseInt(pag[0].pagina) + 1) && i <= 4; i++) {

                        output += '<div class="bs-docs-section btn_COMANDA">\n\
                                <div class="bs-glyphicons">\n\
                                    <ul class="bs-glyphicons-list">';

                        for (var y = 1; y <= 6; y++) {
                            for (var x = 1; x <= 8; x++) {

                                var posizione_attuale = y + "-" + x;
                                var query_prodotti = 'SELECT cat_varianti,colore_tasto,id,descrizione,prezzo_1 FROM prodotti WHERE categoria="' + cat[0].id + '" AND pagina="' + pag[0].pagina + '" AND posizione="' + posizione_attuale + '" LIMIT 1;';

                                //console.log(query_prodotti);


                                comanda.sincro.query(query_prodotti, function (oggetto) {


                                    //console.log(typeof(oggetto.prodotto[0]));
                                    if (oggetto !== undefined && oggetto[0] !== undefined && oggetto[0]['descrizione'].length > 0)
                                    {
                                        var prodotto = oggetto[0];

                                        //console.log(prodotto);

                                        output += '<li class="btn_comanda" style="background-color:' + prodotto["colore_tasto"] + ';" onClick="aggiungi_articolo("' + prodotto["id"] + '","' + prodotto["descrizione"] + '","' + prodotto["prezzo_1"] + '&euro; ","null",$("#quantita_articolo").val(),"null","' + prodotto["cat_varianti"] + '");"> \n\
                                 <span class="glyphicon-class">' + prodotto['descrizione'] + '<br/>€ ' + prodotto['prezzo_1'] + '</span> \n\
                                 </li>';
                                    }
                                    else
                                    {
                                        output += '<li style="display:table;"> \n\
                                 <span class="glyphicon" aria-hidden="true"></span> \n\
                                 <span class="glyphicon-class"></span> \n\
                                 </li>';
                                    }


                                });
                            }
                        }

                        output += '</ul></div></div></div>'; //chiude le intestazioni
                        resolve({output:output});
                        //alla fine deve creare una pagina in piu, ma il massimo è 4 pagine
                    }
                });
            }
            ;
        });
    });
    promises.push(promessa);


    Promise.all(promises).then(function (data) {
        callBack(data[0].output);
        });
   };
 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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