promise ,async 小记

Promise

Promise 对象用于表示一个异步操作的最终状态(完成或失败),以及该异步操作的结果值。

摇色子游戏,随机1-6的一个整数,并且将其返回。

function fn() {
return new Promise((resolve, seject) => {
setTimeout(() => {
let n = parseInt(Math.random) * 6 + 1,10// 1-6
resolve(n)
}, 3000)
})
}

fn().then(
  (x) => { console.log('色子的点数是' + x) },
  () => { console.log('色子坏了')}
)

 

async和await

**async function** 声明用于定义一个返回 AsyncFunction 对象的异步函数。异步函数是指通过事件循环异步执行的函数,它会通过一个隐式的 Promise 返回其结果。但是如果你的代码使用了异步函数,它的语法和结构会更像是标准的同步函数。

async function 声明异步函数

function 声明同步函数

function fn() {
return new Promise((resolve, seject) => {
setTimeout(() => {
let n = parseInt(Math.random) * 6 + 1,10// 1-6
resolve(n)
}, 3000)
})
}

async function test() {
   let n = await fn();
   console.log(n)
}

test()

再增加try...catch语句来捕获异常

function fn() {
return new Promise((resolve, seject) => {
setTimeout(() => {
let n = parseInt(Math.random) * 6 + 1,10// 1-6
           if (n>3){
               if (猜测 === '大') {
               resolve(n)
              } else {
                   reject(n);
              }
          } else {
               if (猜测 === '小') {
               resolve(n)
              } else {
                   reject(n);
              }
          }  
}, 3000)
})
}

async function test() {
   try {
let n = await fn("大");
  console.log("好嗨哟" + n)
  }catch (error) {
console.log("输光了" + n)
  }  
}

fn("大").then(f1, f2).then(f3, f4)
test()

为什么不使用promise.then,而使用async await?

使异步代码看起来更像是同步代码,async await看起来更清晰简单

 

如果有两个色子,并且猜大小都猜对了才算成功,该怎么做呢?

扫描二维码关注公众号,回复: 6889236 查看本文章

Promise.all() 这个方法返回一个新的promise对象,该promise对象在iterable参数对象里所有promise 对象都成功的时候才会触发成功,一旦有任何一个iterable里面的promise对象失败则立 即触发该promise对象的失败。

Promise.race() 当iterable参数里的任意一个子promise被成功或失败后,父promise马上也会用子 promise的成功返回值或失败详情作为参数调用父promise绑定的相应句柄,并返回该 promise对象。

function 猜大小() {
return new Promise((resolve, seject) => {
setTimeout(() => {
let n = parseInt(Math.random) * 6 + 1,10// 1-6
           if (n>3){
               if (猜测 === '大') {
               resolve(n)
              } else {
                   reject(n);
              }
          } else {
               if (猜测 === '小') {
               resolve(n)
              } else {
                   reject(n);
              }
          }  
}, 3000)
})
}

Promise.all([猜大小('大'), 猜大小('小')])
.then(() => {}, () => {})

async function test() {
   try {
let n = await Promise.all([猜大小('大'), 猜大小('小')]);
  console.log("好嗨哟" + n)
  }catch (error) {
console.log("输光了" + n)
  }  
}

 

猜你喜欢

转载自www.cnblogs.com/yaokai729/p/11261264.html
今日推荐