Promise - all race async await

387 阅读1分钟

Promise的方法

    <script>
        function http1(){
            return new Promise((resolve,reject)=>{
                setTimeout(()=>{
                    resolve('今天喝Coco奶茶')
                },3000)
            })
        }
        function http2(){
            return new Promise((resolve,reject)=>{
                setTimeout(()=>{
                    resolve('什么奶茶都不喝')
                },2000)
            })
        }

(1)all()

两个请求需要同时调用,并且接口数据需要一起出来。

        Promise.all([http1(), http2()]).then(res => {
            console.log(res) //这个返回值是一个数组
            /* 需求 :需要两个接口的数据都返回了再渲染页面 */
            document.write(res[0]);
            document.write(res[1]);
        })
    </script>

(2)race()

同时调用多个接口,谁的接口出现的数据快就用谁的。

        Promise.race([http1(), http2()]).then(res => {
            /* 返回值是出现的速度最快的接口的数据 */
            console.log(res)
            document.write(res);
        })
    </script>

(3)async await

以下两端代码实现的效果是一样的。

  onLoad: function () {
    indexHttp('/api/index', {}, 'GET').then(res => {
      this.setData({
        slides: res.slides,
        itemList: res.goods.data
      })
    }).catch(err => { console.log(err); })
  },
  onLoad: async function () {
    try {
      let res = await indexHttp('/api/index', {}, 'GET');
      this.setData({
        slides: res.slides,
        itemList: res.goods.data
      })
    } catch (err) { console.log(err) }
  },