Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在函数内部定义外部范围变量_Javascript_Arrays_Node.js_Json_Express - Fatal编程技术网

Javascript 在函数内部定义外部范围变量

Javascript 在函数内部定义外部范围变量,javascript,arrays,node.js,json,express,Javascript,Arrays,Node.js,Json,Express,我正在为表单的一个字段服务器端(expressjs)构建验证,并为此执行以下操作: const contains = (arr1, arr2) => { arr2.every(v => arr1.indexOf(v) !== -1) } var match; fs.readFile('../tags.json', 'utf8', (err, data)=>{ var JsonData = JSON.parse(data); var tagsArray = Json

我正在为表单的一个字段服务器端(expressjs)构建验证,并为此执行以下操作:

const contains = (arr1, arr2) => {
  arr2.every(v => arr1.indexOf(v) !== -1)
}
var match;
fs.readFile('../tags.json', 'utf8', (err, data)=>{

  var JsonData = JSON.parse(data);
  var tagsArray = JsonData.tags;
  console.log(tagsArray)
  console.log(tags)
  if(tagsArray instanceof Array){
    console.log('tagsArray is array')
  }
  if(!contains(tagsArray, tags)){
    match = false
  }   
  else{
    match = true
  }
  console.log(match + ' blah1')

});

console.log(match + ' blah2')
if(match == false){
  return res.status(409).send({
    message: 'Do not provide your own tags'
  });
}
  • 从json文件读取数据

  • 从中获取属性(数组)

  • 检查它是否包含用户生成数组的每个元素,仅此而已,例如:

  • 因此,我使用此代码:

    const contains = (arr1, arr2) => {
      arr2.every(v => arr1.indexOf(v) !== -1)
    }
    var match;
    fs.readFile('../tags.json', 'utf8', (err, data)=>{
    
      var JsonData = JSON.parse(data);
      var tagsArray = JsonData.tags;
      console.log(tagsArray)
      console.log(tags)
      if(tagsArray instanceof Array){
        console.log('tagsArray is array')
      }
      if(!contains(tagsArray, tags)){
        match = false
      }   
      else{
        match = true
      }
      console.log(match + ' blah1')
    
    });
    
    console.log(match + ' blah2')
    if(match == false){
      return res.status(409).send({
        message: 'Do not provide your own tags'
      });
    }
    
    但它在
    fs.readFile
    块内总是返回false,因为它在
    fs.readFile
    块外返回undefined,所以这意味着包含函数return undefined(我测试了它)

    那么,这方面的线索是什么?
    谢谢

    fs.readFile
    是异步的,因此任何依赖于其结果(正在读取的文件)的代码都需要进入回调函数。(回调函数是
    (err,data)=>{…}
    部分。)

    console.log(match+'blah2')
    if(match==false){…}
    部分移动到回调内部(在blah1行之后)

    您还可以查看或使用允许您避免使用回调函数的

    另一方面,您需要确保始终到达
    res.send()
    行,即在您的情况下
    match==true
    时。否则,当匹配为true时,http请求将不会返回

    编辑:

    下面是express的基本结构,主要是伪代码和注释,仅用于说明回调:

    app.post('/tags', (req, res) => {
    
      // your setup code here
    
      fs.readFile('../tags.json', 'utf8', (err, data) => {
    
        console.log('readFile has finished')
    
        // now you have heard back from readFile
        // check the err and send 500 if there was a problem
        // otherwise work with the file in the var data
    
        // any other db-related stuff also goes in here, which probably
        //   has its own callback you need to use
        db.save(data, (err) => {
          // db call is done, potentially with an error
          // Here you can use `res` to send http response
        })
        // !! again here the db is still doing its work
      })
    
      // !! anything you add here will be executed before readFile is done
      console.log('readFile is probably still at work')
    
    })
    

    我还应该指出,您希望
    contains
    返回bool值,即
    返回arr2。每个(…)
    您可以使用异步/wait

    async function read(){
    let data = await fs.readFile(<path>);
    console.log(data); //You can use data everywhere within this scope
    }
    
    异步函数读取(){ 让data=wait fs.readFile(); console.log(data);//您可以在这个范围内的任何地方使用数据 }
    if-i-move-if语句在回调函数中可能重复它会导致错误:发送头后不能设置头,因为我不太喜欢同步函数,因为它会阻塞线程,我想要异步解决方案,但顺便问一下,在这种情况下,哪一个更可取(我知道这是可选的,但如果你想解决这个问题,你会使用哪一个)?我的意思是,因为我第一次遇到这种问题,headers错误可能是一个单独的问题。我可以通过将这6行移到回调中来解决问题。Re:a/sync,您的一般方法很好。请参阅@eol提供的链接,以了解更多关于它的工作原理。是的,您可以,但我不能,因为此函数位于router.post内部,我在该块之后发送状态代码,因此它确实会导致错误,请勿在回调外部发送状态代码。