Promise链式调用小笔记

1.需要多次循环请求,并且最后一次请求结束后返回请求信息

 Promise.all(
          this.imgList.map((item) => {
            return new Promise((resolve, reject) => {
              // 替换为你的请求
              this.$http
                .post(`${window.ROOT_URL}api/v2/user/upload/doAction`, {
                  image: item.content,
                  directory: "comment",
                  type: "image",
                })
                .then((res) => {
                  if (res.data.code == 0) {
                    console.log(res.data,'666');
                    var imageObj = {
                      file_image: res.data.data.fileUrl,
                      file_thumb: res.data.data.thumb_url,
                    };
                    this.commentUrl.push(imageObj);
                  } else {
                    this.commentUrl = [];
                  }
                  //所以请求结束后拿到的数据
                  return resolve({
                    code: res.data.code,
                    message: res.data.message,
                  });
                });
            });
          })
        ).then((res) => {
          const result = res.filter((v) => {
            return v.code === 1;
          });
          if (result.length > 0) {
            Toast(` 图片大小不能超过${result[0].message[6]}M,请重新上传。`);
          }
          else {
            const newFormData = {
              comment_image: this.commentUrl,
              content: this.textarea,
              comment_id: 0,
              comment_rank: Number(this.rank),
              rec_id: Number(this.$route.params.id),
            };
            this.$store
              .dispatch("setAddgoodscomment", newFormData)
              .then((res) => {
                if (res.code == 0) {
                  this.$router.go(-1);
                  // this.$router.push({
                  //     name: 'comment'
                  // });
                  Toast.clear();
                  Toast({
                    message: "评论成功",
                    duration: 1000,
                  });
                } else {
                  Toast.clear();
                  Toast(this.$t("lang.comment_fail"));
                }
              })
              .catch((err) => {
                Toast.clear();
                Toast(this.$t("lang.comment_fail"));
              });
          }
        });
      }

2.连续.then调用

 //1.返回一个Promise
 getAesEncode() {
          return new Promise((resolve,reject)=>{
            this.$http
                .get(`${window.ROOT_URL}api/v2/common/getAesEncode`)
                .then((res) => {
                    resolve(res.data.data)
                    this.aesEncodeKey = res.data.data;
                });
          })
     },

 //2.直接.then调用
 this.getAesEncode().then(res=>{
    //调用成功的函数
    this.handleLogin();
 })

猜你喜欢

转载自blog.csdn.net/weixin_40565812/article/details/126252518