繁体   English   中英

访问全局变量javascript

[英]Accessing global variable javascript

我正在尝试使用nodejs,javascript下载网页。 但是,它似乎有无限循环。 为什么?

var downloadFinished = false;

var downloadPage = function(url,file) {
  rest.get(url).on('complete', function(result) {
  if (result instanceof Error) {
    console.log('Error:', result.message);
  } else {
    fs.writeFileSync(file, result, 'utf8');
    downloadFinished = true;
   }   
  }); 
};

if(require.main == module) {
    downloadPage('http://google.com', 'new.html');
    while(!downloadFinished) {
       // wait till download finished.
    } 
    // do other stuff make sure download is finished to 'new.html'
}

Javascript是单线程的,如果您有如下循环:

while(!downloadFinished) {

}

该循环将永远运行,并且没有其他功能将运行( .on('complete'的单线程特性,直到while循环结束后,您的.on('complete'回调函数才能执行,因此,由于您请勿在该循环内设置downloadFinished = true或使用break语句)。

要解决此问题,您可以在回调中完成所有其他工作,直到下载完成才调用:

var downloadPage = function(url, file, callback) {
  rest.get(url).on('complete', function(result) {
    if (result instanceof Error) {
      console.log('Error:', result.message);
    } else {

      /* Don't use writeFileSync, unless you want to block your server,
        from handling any requests at all until the disk IO completes

        fs.writeFileSync(file, result, 'utf8');
        callback();
      */
      fs.writeFile(file, result, 'utf8', callback);
    }   
  }); 
};

if(require.main == module) {
    downloadPage('http://google.com', 'new.html', function after_download(){
        // do other stuff make sure download is finished to 'new.html'
    });
}

当您调用while(!downloadFinished)它将被设置为false,因此您基本上就是在进行while(true)

选项1

您可以使用回调而不是while循环。

var successCallback = function() {
 //do stuff here.
};

var downloadPage = function(url, file, callback) {
  rest.get(url).on('complete', function(result) {
  if (result instanceof Error) {
    console.log('Error:', result.message);
  } else {
    fs.writeFile(file, result, 'utf8', callback);
   }   
  }); 
};

if(require.main == module) {
    downloadPage('http://google.com', 'new.html', successCallback);
}

选项2

查看Promise,他们将在这里为您提供真正的帮助。 您可以使用Bluebird一个不错的Promise库,您可以将其添加到程序包依赖项中。

暂无
暂无

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

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