- JS回调函数中无法改变外部变量的问题
# abc = res 操作的时候,res还没有结果
var abc;
Article.findArticle({}, function (err, res) {
    if (err) {
        console.log(err);
    } else {
        //操作查询出的文章
        abc = res;
    }
});
https://blog.csdn.net/qq_23870025/article/details/77920898
- 遇到问题,无法push内容到外部的列表
var dirList = [];
var fileList =[];
files.forEach(function(iterm){
  var fullPath =  path.join(wwwDir,iterm);
  // 异步  这里异步处理会无法修改外部的list,data的结果滞后于代码执行【不知道这样理解对不对】
  fs.stat(fullPath, function(err, data){
    if (err) {
        console.log(err);
    } else {
        if (data.isFile()){
          fileList.push(iterm)
          // console.log('file: ',fileList)
        }else{
          dirList.push(iterm)
        }
    }
  });
  // 同步 
  var stat = fs.lstatSync(fullPath);
  console.log(fullPath,stat.mtime)
  if (stat.isFile()){
    fileList.push({'fullPath':fullPath,'fileSise':stat.size,'mtime':stat.mtime});
  }else{
    console.log(fullPath)
    dirList.push(fullPath);
  }
});
console.log('dir: ',dirList)
console.log('file: ',fileList)
- JS异步api的封装【必须通过回调函数】【回调函数作用:获取异步的结果】
// 模板概念
function fn(callback) {
  // var callback = function (data) { console.log(data) }
  setTimeout(function () {
    var data = 'hello'
    callback(data)
  }, 1000)
}
// 如果需要获取一个函数中异步操作的结果,则必须通过回调函数来获取
fn(function (data) {
  console.log(data)
})
//应用
/*
*获取所有学生列表
*callback
* 第一个参数是err
    成功是null
    错误 错误对象
* 第二个参数是 结果
    成功是 数组
    错误 undefined
*/
exports.find = function (callback) {
  fs.readFile(dbPath, 'utf8', function (err, data) {
    if (err) {
      return callback(err)
    }
    callback(null, JSON.parse(data).students)
  })
}
//调用【find使用方法】
var Student = require('./student')
router.get('/students', function (req, res) {
  Student.find(function (err, students) {
    if (err) {
      return res.status(500).send('Server error.')
    }
    res.render('index.html', {
      fruits: [
        '苹果',
        '香蕉',
        '橘子'
      ],
      students: students
    })
  })
})