map循环调用接口并发问题

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

代码中使用了`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)
          })
   }
}

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)
            })
         }
       }
    }
    
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值