手撕Promise真面目(初探 async 函数 与 awate

2020-11-05  本文已影响0人  酷酷的凯先生

# 前言

async 函数:
async 函数 的返回值是 Promise 对象
Promise 对象的结果由 async 函数 执行的返回值决定

await表达式:
awate 右侧表达式一般为 Promise 对象,但也可是其他值
如果是 Promise 对象,awate 返回值就是 Promise 成功的值
如果是其他的值,直接将此值作为 awate 的返回值

注意
await 必须写在 async 函数中,但 async 函数 中可以没有 await
如果 awaitPromise 失败了,就会抛出异常,需要 try...catch 来捕获处理
await 只能 拿到 Promise成功 的值,想要拿到失败或异常的值,只能通过 try... catch 来捕获

# async 函数

async 函数返回一个 Promise 对象
而返回的 Promise 结果由函数执行的结果决定

// 未加 async 之前
function fn(){
    return 1;
}

const result = fn();
console.log(result); // 1

// 加上 async 之后
function fn(){
    return 1;
}

const result = fn();
console.log(result);
 
/* 输出结果为 Promise 对象
* Promise {<fulfilled>: 1}
* __proto__: Promise
* [[PromiseState]]: "fulfilled"
* [[PromiseResult]]: 1
*/

// 想要拿到 result 的结果只能通过 then()
result.then(
  value =>{ console.log('onResolved()', value) },
  reason => { console.log('onRejected()', reason) }
)
这时输出结果为:onResolved() 1

# await表达式

// 情景一:
function fn1(){
  return new Promise((resolve, reject)=>{
    setTimeout(()=>{
      resolve(1);
    },2000)
  })
}

async function fn2(){
  // await 右侧表达式为 Promise,得到的结果就是 Promise 成功的 value 
  const result = await fn1();
  console.log(result )
}

fn2();  // 等待 2 秒后 输出 1

// 情景二:
function fn1(){
  return 1;
}

async function fn2(){
  // await 右侧表达式为非 Promise ,得到的结果就是它本身
  const result = await fn1();
  console.log(result)
}

fn2();  // 直接输出 2

// 情景三:
function fn1(){
  return new Promise((resolve, reject)=>{
    setTimeout(()=>{
      reject(1);
    },2000)
  })
}

async function fn2(){
  try{
    // await 的 Promise 失败需要 `try...catch` 捕获来拿到错误信息,抛出异常也是如此
    const result = await fn1();
  }catch(error){
    console.log(error)
  }
}

fn2();  // 等待 2 秒后 输出 1
上一篇 下一篇

猜你喜欢

热点阅读