gpt4 book ai didi

node.js - while循环代码在node js中没有顺序执行

转载 作者:太空宇宙 更新时间:2023-11-04 01:48:56 26 4
gpt4 key购买 nike

尝试在while循环中执行代码并设置标志,但无法设置标志,它带有初始标志值。我的代码如下:

var flag = 0
while(!flag)
{
connection.query('SELECT nlc,id,user_id FROM tbl_buy WHERE `type`="buy" AND `status`="available" AND coin_id="'+jsondata.coinid+'" AND order_type="market" order by id ASC LIMIT '+offset+',1',function (error,results, fields)
{
if(results.length > 0)
{
flag = 1; // want to set flag when i recieve the result
connection.query('SELECT tbl_buy.* from (select tbl_buy.*, (@sum := @sum + nlc) as cume_stock from tbl_buy cross join (select @sum := 0) params WHERE tbl_buy.type="sell" AND tbl_buy.status="available" AND tbl_buy.user_id!="'+results[0].user_id+'" AND tbl_buy.coin_id="'+jsondata.coinid+'" AND tbl_buy.order_type="market" order by id ) tbl_buy where cume_stock-nlc < "'+results[0].nlc+'"',function (error,results_arr, fields)
{
res.end(JSON.stringify(results_arr));
myCallback(results,results_arr);
});
}
});
console.log('flag value : '+flag); // this line executes first and then the query is been executed , here the value remains same (ie flag = 0 and not changed to 1)
offset++;
}

不明白为什么控件转到 console.log('flag value : '+flag);而不是顺序执行

最佳答案

因为 Node 是异步的。这就是为什么当您的查询阻塞处理时,它将您的代码插入事件循环并在您的情况下执行下一条语句console.log('flag value : '+flag);

关于node.js - while循环代码在node js中没有顺序执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50422757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com