在map循环内调用接口产生并发问题

508 阅读1分钟

项目中有个需求是从本地数据库查询数据,查询到数据后请求后端接口修改数据。查询出来的数据可能有多条且是重复的。理想的状态是逐条执行,就是第一条数据处理成功后,再进行第二次请求。

代码中使用了async/await关键字,但是并没有起作用。

list.map(async item => {
    if (item.type === 0) {
          // 绑定
          const params = {
            materialCode: item.material_code,
            batchNumber: item.batch_number,
            inCode: item.in_code,
            deviceCode: this.mac,
            type: 0, // 绑定
            deliveryNo: item.delivery_number
          }
          console.log('------------------------------------')
          await this.service.api.productionInfoBinding(params).then(res => {
              console.log('生产信息res:', res)
          })
   }
}

async/await不起效的原因:

await是异步转同步的写法,但并不会阻塞主线程的同步进行的代码,只会阻塞异步代码

forEach/map这样的高级循环遍历函数,在循环的同时,是不能更改内部item对象的(map更改后,返回的是新数组,forEach是原数组被更改),所以在map使用await不起作用。

我们改为for循环就可以了,代码如下:

async handleProductInfo() {
    let { list } = await this.service.storage.getDataInsertFailed('product_info')
 
    if(list.length){
       for(let i=0;i<list.length;i++){
         if(list[i] === 0){
            const params = {}
            console.log('123')
            await this.service.api.xxxx(params).then(res => {
                console.log('res:',res)
            })
         }
       }
    }
    
}