简体   繁体   English

NodeJS可变碰撞? 与请求异步/同步

[英]NodeJS Variable Collision? Async / Sync with Request

Issue : Data INFO_X sometimes and randomly become Null. 问题:数据INFO_X有时会随机变为Null。

Question , 题 ,

Does the variable overwrites each other for INFO_1 INFO_2 INFO_3 since Nodejs run fast unlike PHP it follows a sequence/step by step. 变量是否为INFO_1 INFO_2 INFO_3互相覆盖,因为Nodejs与PHP不同,它运行速度很快,因此遵循一个序列/一个步骤。

I checked for NULLS before doing a request but the debug shows it's NOT NULL before executing the 2nd request, at random, random variables will become null upon submitting the 2nd request. 我在执行请求之前检查了NULL,但调试显示在执行第二个请求之前它不是NULL,随机地,在提交第二个请求时随机变量将变为null。

I also checked my source is definitely not returning any null. 我还检查了我的来源是否绝对不返回任何null。

Is the variable being overwritten before the 2nd request is sent or what? 在发送第二个请求之前,该变量是否被覆盖? Please advice. 请指教。

var request = require('request');

var urls = [ 'URL',
             'URL',
             'URL'];

urls.forEach(processUrl);

function processUrl(url) {

  request(url, function (error, response, body) {
  if (!error) {
    var obj = JSON.parse(body);
     for (var i = 0, len = obj['products'].length; i < len; ++i) {
         var data = obj['products'][i];
         var INFO_1 = data.INFO_1
         var INFO_2 = data.INFO_2
         var INFO_3 = data.INFO_3

        request("URL/POSTINFO?INFO_1="+INFO_1+"&INFO_2="+INFO_2+"&INFO_3="+INFO_3+"&seller_id=", function(error, response, body) {
            console.log(body);
        });

     }
  }
});

}

Yes, that is the case, because request function is asynchronous. 是的,就是这种情况,因为请求功能是异步的。 I wouldn't call nodejs "faster" than PHP, it just runs asynchronous request methods, while PHP is generally synchronous. 我不会称nodejs比PHP“更快”,它只运行异步request方法,而PHP通常是同步的。

You could resolve the issue with promises, eg Promise.all([]) and provide an array of request functions (see here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all ), or in your case, use this library https://github.com/caolan/async#forEach 您可以使用Promise.all([])来解决问题,并提供一系列请求函数(请参见此处: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise / all ),或者在您的情况下,使用此库https://github.com/caolan/async#forEach

Since you're using callbacks in the request function, your best option is to use async as provided in the link above. 由于您在request函数中使用了回调,因此最好的选择是使用上面链接中提供的async Here's an example code: 这是一个示例代码:

    function request(url, cb) {
      setTimeout(() => {
        cb(url + ' accessed at ' + new Date());
      }, 2000);

    }

    var urls = ['URL1', 'URL2', 'URL3'];

    async.each(urls, (item) => {
      console.log(item);
      request(item, (value) => {
        request(value, (newValue)=>{
          console.log(newValue);
        });
      });
    }, (err) => {
      console.log(err);
    });

Here's a working example: https://plnkr.co/edit/Q5RAvKdaLxV9cUT4GP4w?p=preview 这是一个工作示例: https : //plnkr.co/edit/Q5RAvKdaLxV9cUT4GP4w?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM