如何从节点js中for循环内的数据库中获取数据

时间:2017-05-24 05:07:29

标签: javascript mysql node.js

使用节点js中的池查询在for循环内获取数据输出值是正确的但不在正确的位置。 这是我的代码。

[ RowDataPacket { cnt_deal_amt: null } ]
[ RowDataPacket { cnt_deal_amt: 512529 } ]
[ RowDataPacket { cnt_deal_amt: null } ]
[ RowDataPacket { cnt_deal_amt: 43600 } ]
[ RowDataPacket { cnt_deal_amt: 0 } ]
[ RowDataPacket { cnt_deal_amt: 9500 } ]
[ RowDataPacket { cnt_deal_amt: 33000 } ]
[ RowDataPacket { cnt_deal_amt: null } ]
[ RowDataPacket { cnt_deal_amt: 0 } ]
[ RowDataPacket { cnt_deal_amt: 1000 } ]
[ RowDataPacket { cnt_deal_amt: 11500 } ]
[ RowDataPacket { cnt_deal_amt: null } ]
刷新页面时,每次更改位置时,

输出结果值也不在正确的位置。

.ratio-box {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: calc(100% * 600 / 600); // If you want other ratio, for example 3x4, this line will be: `padding-bottom: calc(100% * 4 / 3)`
}
.img-wrapper {
    position: absolute;
    width: 100%;
    height: 100%;
}
.img-wrapper img {
    display: block;
    position: absolute;
    /* Center alignment */
    margin: auto;
    top: -9999px;
    bottom: -9999px;
    left: -9999px;
    right: -9999px;
}
.img-wrapper img.landscape { /* For images have natural width >= height */
    width: auto;
    height: 100%;
}
.img-wrapper img.portrait { /* For images have natural width < height */
    width: 100%;
    height: auto;
}

2 个答案:

答案 0 :(得分:0)

节点js是异步的,并且在执行循环时不能保留顺序。节点循环的行为与其他语言不同。 我会建议你使用回调来保留顺序的替代解决方案。

var k = 0;
function query(cb) {
    var mdmid_arr= mdmid_array_implode_array_st[k];
    var my_query = "select sum(cnt_deal_amt) as cnt_deal_amt from crm_clients_feedback_log where cnt_mdm_id IN ("+mdmid_arr+") ORDER BY cnt_mdm_id ASC";
    pool.query(my_query,cb);
}

var result = function(dealerr,dealrslt){
    dealrslt_sa=dealrslt[0].cnt_deal_amt;
    console.log(dealrslt);
    k ++;
    if(k < mdmid_array_implode_array_st.length) {
        setTimeOut(query,0,result);
    }   
}

query(result);

答案 1 :(得分:0)

这可能是处理此类任务(使用Promise和async-await ...)的最佳方法。

 var counter = 0;
 const waitFor = (ms) => new Promise(r => setTimeout(r, ms));
 mdmid_array_implode_array_st.forEach(async (num) => {
    await waitFor(50);
    console.log(num);
    /**STARTput whatevever want here... WRITE YOUR QUERY, I just copypasted your code, have not checked yet...**/
    var mdmid_arr=mdmid_array_implode_array_st[counter];
    pool.query("select sum(cnt_deal_amt) as cnt_deal_amt from crm_clients_feedback_log 
    where cnt_mdm_id IN ("+mdmid_arr+") ORDER BY cnt_mdm_id 
    ASC",function(dealerr,dealrslt){
            dealrslt_sa=dealrslt[0].cnt_deal_amt;
            console.log(dealrslt);
    });
    //END************************************
    counter++;
  });

P.S。这对我来说是最好的方法,但是您得到的是空值,请专注于sql查询,但我建议通过-> forEach <-使用诺言和async-await ,而不是直接应用-> for <-循环。