Nodejs同步对于每个循环 [英] Nodejs Synchronous For each loop

查看:66
本文介绍了Nodejs同步对于每个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为每个循环做一个,但是让它同步运行.循环的每次迭代都将执行http.get调用,并返回json以将值插入数据库中.问题是for循环异步运行,这导致所有http.gets一次全部运行,并且我的数据库最终没有插入所有数据.我正在使用async-foreach尝试执行我想要的操作它可以做到,但是如果我能以正确的方式做到这一点,我就不必使用它.

I want to do a for each loop but have it run synchronously. Each iteration of the loop will do an http.get call and that will return json for it to insert the values into a database. The problem is that the for loop runs asynchronously and that causes all of the http.gets to all run at once and my database doesn't end up inserting all of the data.I am using async-foreach to try to do what I want it to do, but I don't have to use it if I can do it the right way.

mCardImport = require('m_cardImport.js');
var http = require('http');
app.get('/path/hi', function(req, res) {

mCardImport.getList(function(sets) {
  forEach(sets, function(item, index, arr) {
    theUrl = 'http://' + sets.set_code + '.json';
    http.get(theUrl, function(res) {

      var jsonData = '';
      res.on('data', function(chunk) {
        jsonData += chunk;
      });

      res.on('end', function() {
        var theResponse = JSON.parse(jsonData);
        mCardImport.importResponse(theResponse.list, theResponse.code, function(theSet) {
          console.log("SET: " + theSet);
        });
      });
    });
  });
});
});

和我的模特

exports.importResponse = function(cardList, setCode, callback) {

mysqlLib.getConnection(function(err, connection) {

forEach(cardList, function(item, index, arr) {

  var theSql = "INSERT INTO table (name, code, multid, collector_set_num) VALUES "
   + "(?, ?, ?, ?) ON DUPLICATE KEY UPDATE id=id";
  connection.query(theSql, [item.name, setCode, item.multid, item.number], function(err, results) {
    if (err) {
      console.log(err);
    };
  });
});
});
callback(setCode);
};

推荐答案

我发现我在完成每次调用后都没有释放mysql连接,这将连接捆绑在一起,导致连接失败并看起来像是同步问题.

I found out that I wasn't releasing my mysql connections after I was done with each call and this tied up the connections causing it to fail and appear to be an issue with synchronization.

显式调用connection.release();后,即使以异步方式,它也使我的代码可以100%正确地工作.

After explicitly calling connection.release(); it caused my code to work 100% correctly even in an asynchronous fashion.

感谢发布此问题的人.

这篇关于Nodejs同步对于每个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆