鸿蒙学习 - Promise异步

48 阅读1分钟

鸿蒙学习 - Promise异步


@Entry
@Component
struct Index {

  // 封装Promise结果的方法
  testPromiseAction() {
    return new Promise((resove,reject) => {
      setTimeout(()=> {
        const random = Math.random()
        if (random > 0.5) {
          resove("成功了") // then里面获取
        } else {
          reject("失败了") // catch里面获取
        }
      }, 3000) // 延迟几秒
    })
  }


  build() {
    Column(){
      // 用法一:
      Button("click").onClick( async () => {
        try {
          let res = await this.testPromiseAction()
          console.log(res as string)
          console.log("test1") // 这句会阻塞!!!
        } catch (e) {
          console.log("catch了:" + e)
        }
        console.log("test2") // 这句会阻塞!!!
      })

      // 用法二:
      // Button("click").onClick( () => {
      //   // 直接用then的方式调用,不需要await和 async了
      //   this.testPromiseAction().then(res=> {
      //     console.log(res as string)
      //   }).catch(error=> {
      //     console.log("catch了:" + error)
      //   })
      //
      //   console.log("test") // 这句会立即打印,不会阻塞
      // })


    }
  }
}