简体   繁体   English

两个不同的POST请求正在使用相同的变量

[英]Two different POST requests are making use of the same variable

I have a node app that receives a post request with multiple objects to add to a database and for object a series of things needs to happen that involve the dropbox api. 我有一个节点应用程序,该应用程序接收带有多个对象的发布请求,以将其添加到数据库中,并且对于对象,需要发生涉及dropbox api的一系列事情。 It takes around 0.5 seconds to complete the full set of tasks for an object. 完成一个对象的全部任务大约需要0.5秒。 This means that if i submit an array of 30 objects this can take 15 seconds. 这意味着,如果我提交30个对象的数组,则可能需要15秒。

When two clients post 30 objects their processing will overlap. 当两个客户发布30个对象时,它们的处理将重叠。 I have a variable in the function where this happens that stores the issues with the handling of each case. 我在函数中有一个发生这种情况的变量,该变量存储了每种情况下的处理问题。 However when to requests are posted and the running overlaps the errors from both post requests go into the same issues array. 但是,什么时候发布请求,并且运行重叠,则两个发布请求中的错误都会进入同一issues数组。 How do I get the server to call two separate versions of the bulkAdd function. 如何使服务器调用bulkAdd函数的两个单独的版本。

bulkAdd: async function (req, callback) {
  issues = []

  await req.reduce((promise, audit) => {
    // return promise.then(_ => dropbox_functions.createFolder(audit.scanner_ui)
    let globalData;
  return promise.then(_ => this.add(audit)
      .then((data)=> {globalData = data; return dropbox_functions.createFolder(data.ui, data)}, (error)=> {issues.push({audit: audit, error: 'There was an error adding this case to the database'}); console.log(error)})
        .then((data)=>{console.log(data, globalData);return dropbox_functions.checkScannerFolderExists(audit.scanner_ui)},(error)=>{issues.push({audit: globalData, error: 'There was an error creating the case folder in dropbox'})})
         .then((data)=>{return dropbox_functions.moveFolder(audit.scanner_ui, globalData.ui)},(error)=>{issues.push({audit: globalData, error: 'No data folder was found so an empty one was created'}); return dropbox_functions.createDataFolder(globalData.ui)})
          .then(()=>console.log(issues))
    );
  }, Promise.resolve()).catch(error => {console.log(error)});
  return(issues)
}, 

Your problem has to do with scope and closure: 您的问题与范围和闭包有关:

issues = []

I'm guessing this variable was declared outside of the bulkAdd method. 我猜这个变量是在bulkAdd方法之外声明的。 If it wasn't, declaring it without a var or let keyword is essentially putting the variable on the global scope. 如果不是,则在不使用varlet关键字的情况下声明它实际上是将变量置于全局范围内。

You need a variable that's locally scoped to the method: 您需要在本地范围内定义方法的变量:

bulkAdd: async function (req, callback) {
  let issues = [];

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

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