oliver1204 / promise

手写一个promise
3 stars 0 forks source link

async/await 函数 #2

Open oliver1204 opened 5 years ago

oliver1204 commented 5 years ago

简介

async/await 用法

async 函数返回一个 Promise 对象,可以使用 then 方法添加回调函数。当函数执行的时候,一旦遇到 await 就会先返回一个 Promise 对象,等到异步操作完成,再接着执行函数体内后面的语句。

我们先来模拟一个请求:

function ajax {
  return new Promise(resolve => {
    setTimeout(resolve, 1000);
  });
}

用then 的方式写,如下:

ajax()
.then(() => {
   console.log(value);
})

上面的方法用async/await 的写法,如下:

let asyncPrint = async (value) => {
  await ajax();
  console.log(value);
}
asyncPrint('hello world');

async/await 错误处理

function ajax() {
  return new Promise(resolve, reject => {
    setTimeout(reject, 5000);
  });
}
async function asyncPrint(value) {
  await ajax();
  return value
}
asyncPrint('hello world')
.then(result=> {
  console.log(result);
})
.catch(err=>{
  console.log(err)
})
function ajax() {
  return new Promise(resolve, reject => {
    setTimeout(reject, 5000);
  });
}
async function asyncPrint(value) {
  try{
    await ajax();
    console.log(value)
  }catch(err){
    console.log(err)
  }
  await ajax();
  return value
}
asyncPrint('hello world');
  1. await 后面紧跟着的最好是一个耗时的操作或者是一个异步操作(当然非耗时的操作也可以的,但是就失去意义了)
  2. 如果 await 后面的异步操作出错,那么等同于 async 函数返回的 Promise 对象被 reject

主动抛出错误

笔者不知道有没有更好的方式,目前笔者借用的是Promise.reject() 方法来处理的。

if(response.success) {
    return response.data
} else {
    return Promise.reject(response); 
}
oliver1204 commented 5 years ago
function* helloWorldGenerator() {
  yield 'hello';
  yield 'world';
  return 'ending';
}

var hw = helloWorldGenerator();
hw.next();
hw.next();
hw.next();
hw.next();
// co 库

function co(it){
    return new Promise((resolve,reject)=>{
        // 异步迭代 next
        function next(data){
           let {value,done} = it.next(data);
           if(!done){
               Promise.resolve(value).then(data=>{
                  next(data)
               },reject);
           }else{
                resolve(value);
           }
        }
        next();
    });
}
co(read()).then(data=>{
    console.log(data);
});

发展趋势: // generator-runtime搜索 generator简单实现 // async + await 就是 generator + co 库 // 回调 -》 promise -》 generator -》 async + await