getting-started-with-javascript icon indicating copy to clipboard operation
getting-started-with-javascript copied to clipboard

请看下面异步函数调用代码,想一个问题,可以保证文件名和文件内容的一致性吗?

Open MyColourfulLife opened this issue 7 years ago • 2 comments

这是getting-started-with-javascript/homework/lesson7/homework_sample.js代码片段

上文:

  //循环读取json文件的内容,并都存在jsonList数组内。读取出错的文件名存在errorFiles数组内。
  var jsonList = [];
  var errorFiles = [];
  for (var i = 0; i < jsonFiles.length; i++) {
    try {
      // 读取json文件
      var content = jsonfile.readFileSync(pathString + jsonFiles[i]);
      jsonList.push(jsonFiles[i]);
    } catch (err) {
      // 如果读取错误就把错误的文件名写入到errorFiles数组内
      errorFiles.push(jsonFiles[i]);
    }
  }

至此已经拿到了jsonList列表。 问题在下面,把老师同步读取函数改为了,异步读取函数。 那么下文注释的解释正确吗?假设没有内容读取错误的文件,jsonList文件内容和jsonFiles文件对应的名字是不是会出现对应错乱的情况?

for (var i = 0; i < jsonFiles.length; i++) {

    jsonFile.readFile(pathString + jsonFiles[i] ,function (err,obj) {
           if (err) {
               console.log('内容读取错误');
               console.log(err);
               errorFiles.push(jsonFiles[i]);
               return;
           }
           //放入数组中 异步回调回来的时机不确定 这里的数组是不是可能会出现 顺序不一致的现象
           jsonList.push(obj);
       })
   }

MyColourfulLife avatar Aug 30 '17 15:08 MyColourfulLife

什么是异步,异步就是你调了它,它不会立马给你结果,而是要等它的处理完。在等它结果回来之前,你自己还在继续运行。

xugy0926 avatar Aug 30 '17 15:08 xugy0926

因为是异步,谁先处理完谁先回来。完全取决于异步的内部处理时间。

xugy0926 avatar Aug 30 '17 15:08 xugy0926