forEach循环遍历请求接口

2019-12-14  本文已影响0人  小白白呐

最近项目的需求,需要遍历table表格里的数据,进行生产的操作,

导入数据以后的样子,初始样子 遍历的方法

效果:

哪个先请求成功就先把哪个的值显示出来

接口返回的格式

潇洒的实现效果

但是有一点需要注意:如果用for循环,就会出现,接口全都请求成功以后,也不能成功赋值的错误!

例如for循环的写法如下:

for循环写法:
postAutoProduceDevice() {

        var _this = this;

        if (_this.zdExList.length < 1) {

          return _this.$message.warning("请先导入要生产的设备");

        }

        var snArr = [];

        var snArrTotal = 0;

        var arrList = _this.zdExList;

        for (let index = 0; index < arrList.length; index++) {

          const element = arrList[index];

          _this.hqUserInfo({

            data: {

              name: "postAutoProduceDevice",

              data: JSON.stringify({

                batch: _this.produceDevSearch.batch,

                devicetype: _this.zd.devtype,

                sn: element.sn,

                field: "",

                snnum: "1",

                operid: _this.userid

              })

            }

          }).then(res => {

            if (res.ret) {

              _this.zdExList[index] = {

                "sn": res.Data[0].sn,

                "deviceType": res.Data[0].devicetype,

                "logicId": res.Data[0].logicid,

                "mac": res.Data[0].mac,

                "ip": res.Data[0].ip,

                "retmsg": "生产成功"

              }

            } else {

              _this.zdExList[index].retmsg = res.Msg;

            }

          });

        }

      },

forEach写法:

postAutoProduceDevice() {

        var _this = this;

        if (_this.zdExList.length < 1) {

          return _this.$message.warning("请先导入要生产的设备");

        }

        var zdParams = {

          batch: _this.produceDevSearch.batch,

          devicetype: _this.zd.devtype,

          sn: "",

          field: "",

          snnum: "1",

          operid: _this.userid

        }

        _this.zdExList.forEach((item,index) => {

          zdParams.sn = item.sn;

          _this.hqUserInfo({

            data: {

              name: "postAutoProduceDevice",

              data: JSON.stringify(zdParams)

            }

          }).then(res => {

            if (res.ret) {

              item.sn = res.Data[0].sn;

              item.devicetype = res.Data[0].devicetype;

              item.logicId = res.Data[0].logicid;

              item.mac = res.Data[0].mac;

              item.ip = res.Data[0].ip;

              item.retmsg = "生产成功";

              _this.$set(_this.zdExList, index, _this.zdExList[index]);

            } else {

              item.retmsg = res.Msg;

              _this.$set(_this.zdExList, index, _this.zdExList[index]);

            }

          });

        });

      },

上一篇下一篇

猜你喜欢

热点阅读