Promise理解:发布功能中的Promise

113 阅读1分钟

做小程序的页面内容发布功能中,由于步骤比较多包括同步异步等等,所以使用Promise来解决问题,结合Promise的三种传入方式(1.普通值,2.Promise对象,3.thenable变量)对Promise的出现和理解有了更深刻的认识。

  • 普通值形式:适用于调用下一个then的切换场景
  • Promise对象形式:适用于由返回的Promise对象决定状态的场景
  • thenable形式:适用于自定义的处理逻辑,对then方法有更多的操作场景。

不需要将所有的使用场景硬背下来,而是应该通过理解记住三种值的形式

  • 普通值
  • Promise对象
  • thenable形式

页面显示

image.png

代码

publish() {
  const { type, image_list, video_src, title, content, location }
   = this.data;

  this.isNotEmpty()
    .then(() => {
      /* 检查非空,准备数据 */

      switch (type) {
        case "image":
          return image_list;
        case "video":
          return [video_src];
      }
    })
    .then((sources) => {
      /* 上传媒体文件 */
      showLoading();
      console.log('------上传媒体文件-------')
      /* 返回Promise对象数组 */
      return this.uploadMedia(sources); 
    })
    .then((res) => {
      /* 提取fileID */
      hiddenLoading();
      console.log("---------提取fileID--------");
      /*返回普通值,调用下一个then方法*/
      return res.map((item) => {
        return item.fileID;
      });
    })
    .then((ids) => {
      /* 上传标题、内容、fileids */
      console.log(ids);
      console.log('----------上传标题、内容、fileids----------')
      /*页面内容的上传 待做*/
      
    })
    .then(res => {
      showSuccessToast({title: '发布成功!'})
      router.redirectToIndex({
        data: {
          flash_with_publish: true
        }
      })
    })
    .catch((err) => {
      hiddenLoading();
      showErrorModal({ title: "发布失败!", content: "请检查网络!" });
    });
},