如何使用nodejs强制执行async.each中的请求?

时间:2017-08-31 14:41:50

标签: javascript node.js foreach async.js requestjs

我有一个async.each,它迭代一个数组,并且对于数组中的每个元素,它执行一个内部有请求的函数“check”。这是代码,但是当我运行它时,我从调试器中看到节点不执行检查功能并阻止其执行。

async.each(array,
  function(v_page, callback){
    if(v_page.url.length>=5){
      internals.check(v_page.url,array2, function (body) {
        callback();
      });
    }
  },
  function(err){
    internals.calls(var1,var2,var3);
});

我尝试使用普通的for循环,但它跳转到internals.calls函数而不执行internals.check函数以获得节点的异步性质。那么如何强制执行检查功能呢?

这是检查功能的代码:

internals.check = (url,array2,cb) => {
  request(url, function(err, recordset) {
    if(err){
      cb(array2);
    }else {
      //some stuffs
      cb(array2)
    }
  });
};

1 个答案:

答案 0 :(得分:4)

仅在// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, dev: { env: require('./dev.env'), port: 8080, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } } 时调用callback,但您需要为每个元素执行此操作:

v_page.url.length >= 5

另一个问题是,您在async.each(array, function(v_page, callback) { if(v_page.url.length >= 5) { internals.check(v_page.url,array2, function(body) { callback(); }); } else { callback(); <== call callback here, when condition is not met } ... 中错误地调用了回调。根据Node.js表示法,回调的第一个参数必须是错误或null(异步使用此表示法)。但是在你的情况下,无论如何你都会用internals.check调用回调:

array2