Js closure value

the interface function is nested to get and change the information, but the second interface function does not get the I value of the loop and tries to pass parameters, but the then method does not know much about
fetchUserList (this.listQuery). Then (response = > {

)
    this.list = response.data.list
    for(var i=0;i < this.list.length;iPP){
      this.list[i] = Object.assign({},this.list[i],this.list[i].sysUser)
      // this.list[i].office = getOfficeInfoById(this.list[i].officeId)
      getOfficeInfoById(this.list[i].officeId).then(response =>{
        this.office = response.data.data.name
        console.log(i)
      })
    }
    console.log(this.list)
    this.total = response.data.total 
    this.listLoading = false
  }) 
  
Mar.23,2021

solve

replace the var in the loop with let
for (let i=0;)

reason

the way you write it. The value of the last I is always taken each time, that is, I is always equal to this.list.length-1

principle

  • what is async

    • is to execute all Synchronize methods before starting to execute asynchronous methods. That is, if your loop is five times, the system will execute the loop code first. After one loop, there will be one asynchronous method at the end, with a total of five asynchronous methods. After the loop code has been executed, the five asynchronous methods will be executed in turn
    • by the time your loop code is finished, I has become 5, so each asynchronous method takes a value of 5
  • what is a closure

    • closure is in an asynchronous method, which can take the value of a variable outside the asynchronous method. Your requirement here is that each asynchronous method takes the I value of the first loop. So local variables must be defined to pass parameters

you can get the value of the loop in the form of closure:
the loop code is modified as follows:

for (var i = 0; i < this.list.length; iPP) {
        this.list[i] = Object.assign({}, this.list[i], this.list[i].sysUser)
        // this.list[i].office = getOfficeInfoById(this.list[i].officeId)
        var _self = this;
        (function (officeId, i) {
            getOfficeInfoById(officeId).then(response => {
                _self.office = response.data.data.name
                console.log(i)
                //
            })
        })(this.list[i].officeId, i)
    }
Menu