【前端】请求远端数据,等数据返回后再进行函数操作方法踩坑

132 阅读1分钟

前端请求远端数据为异步操作,常常数据没有返回就进行函数操作,会导致数据报空错误。博主经过多次研究后总结两种方法,规避异步请求的风险。

一、.then方法。 then是比较普遍的在数据返回后再操作数据的方法。示例如下:

this.loading = true;
try {
	fetch(url, param).then((data) => {
		if (data && data.data && data.code === 200) {
		deal with data;
		}
	);
} catch (error) {
            this.$notify.error({
                title: '提示',
                message: error.message,
            });
} finally {
         this.loading = false;
}

二、运用setInterval轮询数据是否就绪

const that = this;
this.counter = 0; // 设置最大轮询次数
this.timer = setInterval(() => {
     if (that.ObjectA.length !== 0 && that.ObjectB.length !== 0) {
     	 that.dealFunction();
          clearInterval(that.timer);  // 数据就绪,清除轮询器
      }
      if (that.counter > 50) {
          clearInterval(that.timer);  // 超过最大尝试次数,清除轮询器
      }
      that.counter++;
  }, 300);