最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

同步的NodeJS每个循环

IT培训 admin 3浏览 0评论

同步的NodeJS每个循环

我想每个循环做了,但是有它同步运行。循环的每次迭代将做一个http.get调用,这将返回JSON为它值插入到数据库中。问题是,for循环异步运行,并导致所有http.gets的所有运行在一次和我的数据库没有最终将所有的data.I的正在使用异步的foreach尝试做我想做的它做的,但我没有使用它,如果我能做到这一点的正确方法。

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);
};
回答如下:

随着递归的代码是很干净。等待HTTP响应回来再火了一次新的尝试。这将在节点的所有版本。

var urls = ['http://stackoverflow/', 'http://security.stackexchange/', 'http://unix.stackexchange/'];

var processItems = function(x){
  if( x < urls.length ) {
    http.get(urls[x], function(res) {

      // add some code here to process the response

      processItems(x+1);
    });
  }
};

processItems(0);

使用承诺了一个解决方案也将工作做好,更简洁。举例来说,如果你有一个version of get that returns a promise和节点V7.6 +,你可以写这样的例子,它采用了一些新的JS功能异步/ AWAIT功能。

const urls = ['http://stackoverflow/', 'http://security.stackexchange/', 'http://unix.stackexchange/'];

async function processItems(urls){
  for(const url of urls) {
    const response = await promisifiedHttpGet(url);    
    // add some code here to process the response.
  }
};

processItems(urls);

注:这两个例子中跳过错误处理,但你可能应该有在生产应用。

同步的NodeJS每个循环

我想每个循环做了,但是有它同步运行。循环的每次迭代将做一个http.get调用,这将返回JSON为它值插入到数据库中。问题是,for循环异步运行,并导致所有http.gets的所有运行在一次和我的数据库没有最终将所有的data.I的正在使用异步的foreach尝试做我想做的它做的,但我没有使用它,如果我能做到这一点的正确方法。

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);
};
回答如下:

随着递归的代码是很干净。等待HTTP响应回来再火了一次新的尝试。这将在节点的所有版本。

var urls = ['http://stackoverflow/', 'http://security.stackexchange/', 'http://unix.stackexchange/'];

var processItems = function(x){
  if( x < urls.length ) {
    http.get(urls[x], function(res) {

      // add some code here to process the response

      processItems(x+1);
    });
  }
};

processItems(0);

使用承诺了一个解决方案也将工作做好,更简洁。举例来说,如果你有一个version of get that returns a promise和节点V7.6 +,你可以写这样的例子,它采用了一些新的JS功能异步/ AWAIT功能。

const urls = ['http://stackoverflow/', 'http://security.stackexchange/', 'http://unix.stackexchange/'];

async function processItems(urls){
  for(const url of urls) {
    const response = await promisifiedHttpGet(url);    
    // add some code here to process the response.
  }
};

processItems(urls);

注:这两个例子中跳过错误处理,但你可能应该有在生产应用。

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论