promise的使用

1.  new primise

new Promise(function (resolve, reject) {
      console.log(1111);
      resolve(2222);
    }).then(function (value) {
      console.log(value);
      return 3333;
    }).then(function (value) {
      console.log(value);
      throw "An error";
    }).catch(function (err) {
      console.log(err);
    });

执行结果:

 2. return new promise

function print(delay, message) {
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          console.log(message);
          resolve();
        }, delay);
      });
    }
    print(1000, "First").then(function () {
      return print(4000, "Second"); //若不要return又是不一样的结果
    }).then(function () {
      print(3000, "Third");
    });

执行结果: 

3. async await配合promise  vue中使用

mounted() {
        this.getAll()
        this.get()
      },
      methods: {
        async getAll() {
          await this.print(400, '111')
          await this.print(400, '222')
          await this.print(400, '333')
        },
        async get() {
          // 同步执行
          let res = await this.print(400, '444') // 先执行
          console.log(res + 'a') //再执行,

        },
        print(delay, message) {
          return new Promise(function (resolve, reject) {
            setTimeout(function () {
              console.log(message);
              resolve(123);
            }, delay);
          });
        }
      }

4.await 指令后必须跟着一个 Promise

async function asyncFunc() {
      try {
        await new Promise(function (resolve, reject) {
          throw "Some error"; // 或者 reject("Some error")
        });
      } catch (err) {
        console.log(err);
        // 会输出 Some error
      }
    }
    asyncFunc();


async function asyncFunc() {
    let value = await new Promise(
        function (resolve, reject) {
            resolve("Return value");
        }
    );
    console.log(value); //会输出 Return value
}
asyncFunc();

5.

async chongGuo() {
      let res = await new Promise((resolve, reject)=>{ // 同步
        console.log(1);
        resolve('99')
      })
      let res1 =  res
      console.log(res1);
      console.log(2);
    }

执行顺序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值