美文网首页
Promise&async/await

Promise&async/await

作者: 阿亮2019 | 来源:发表于2018-07-27 15:48 被阅读10次

Promise

Promise有三种状态: pending(挂起) fulfilled(成功) rejected(失败)
一般用法

function asyncReadFile() {
  return new Promise((xxx, yyy) => {
       if (true) {
          xxx();
       } else {
          yyy();
      }
  })
}

asyncReadFile()
  .then(() => {

  })
  .catch(() => {

  })

最好只用catch去捕获异常。
发生错误后,后面的then会继续执行。

Promise.resolve()
    .then((res) => {
        console.log(res);
    },err => { // 最好不要在这里捕获异常,这里捕获后,最后的catch会抓不到
        console.log('err');
    })
    .then(() => { // 这里任然会继续执行
        console.log('second');
    })
    .catch(() => {
        console.log('catch'); // 这里不会执行
    });

下一个then不会等上一个then执行完

Promise
    .resolve(1)
    .then((res) => {
        console.log(res);
    })
    .then(() => {
        setTimeout(() => {
            console.log('second');
        })
    })
    .then(() => {
        console.log('third');
    })

output:
1
third
second

必须先执行第二个then完再执行第三个then

Promise
    .resolve(1)
    .then((res) => {
        console.log(res);
    })
    .then(() => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve();
                console.log('second');
            }, 5000)
        })

    })
    .then(() => {
        console.log('third');
    });

promise.all 注意不需要new,

Promise
  .all([Promise.resolve({data: 'bi'})/*requestGet(API.getDefaultGroup)*/, requestGet(API.getAllGroup)])
  .then((res) => {
    res = res || [];
    const defaultData = res[0] || {};
    const AllData = res[1] || {};
    this.groupName = defaultData.data || [];
    this.groupList = AllData.data || [];
})

曾经遇到的一个面试题:实现5秒超时

const p = Promise.race([ // 注意这里不要用 new Promise
    new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(1);
        }, 2000)
    }),
    new Promise((resolve, reject) => {
        setTimeout(() => {
            reject(0);
        }, 5000)
    })
]);

p.then((res) => {
    console.log(res);
}).catch((err) => {
    console.log(err);
});

第二个面试题

console.log(1)
function fn(){
    new Promise(function(){
        console.log(2)
    })
}
fn()
console.log(3)
output: 1 2 3 
hint: Promise 新建后函数立即执行,直接打印2

异步变同步

const f = () => console.log('now');
Promise.resolve().then(f);
console.log('next');
output: next now
const f = () => console.log('now');
(async function test() {
  f();
})()
console.log('next');
output: now next

async/await

await必须写在async函数里面

// 延时
const promiseFun = function (t) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve();
        }, t)
    })
};


(async function run() {
    console.time('tag'); // 记录开始时间
    await promiseFun(3000);

    console.log('这句话要等到3秒结束后才能打印出来!');
    console.timeEnd('tag'); // 记录结束时间 
})();

/*
output:
这句话要等到3秒结束后才能打印出来!
tag: 3001.657958984375ms
*/
// return a Promise Object
const fetch = function (t) {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve();
        }, t)
    })
};

const get = function () {
    return fetch(1000).then(() => {
        return 1
    })
};

const end = function () {
    console.dir(get()); // promise对象
    get().then((res) => {
        console.log(res); // 1
    })
};

end();
// 一些简写形式
const ps = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({
        name: 'Leon',
        age: '18'
      }, 1000)
    })
  })
}

const f = async () => await ps();

!(async function test () {
  const res = await f();
  console.log(res);
})()

// {name: "Leon", age: "18"}

关于async/await的文章更多的可以看
阮一峰 async 函数的含义和用法
边城 理解 JavaScript 的 async/await

相关文章

  • Promise&async/await

    Promise Promise有三种状态: pending(挂起) fulfilled(成功) rejecte...

  • async和await

    浅谈Async/Await用 async/await 来处理异步 async和await async:声明一个异步...

  • ES8(一) —— async&await

    目录 async和普通函数的区别 await async/await处理多回调异步 async和await必须配合...

  • async

    async/await特点 async/await更加语义化,async是“异步”的简写,async functi...

  • ES6中的好东西

    1 Await/Async 前端的回调时代我没有赶上,我赶上的是await/async时代。await和async...

  • Vue接口调用方式(三)async/await用法

    async/await用法 1. async/await的基本用法 async/await是ES7引入的新语法,可...

  • nodejs async 使用简介

    async await node async 使用

  • JS 中的 async/await

    async/await 是什么? async/await 是 ES2017 中新增的异步解决方案; await 只...

  • ES2017 async 函数

    async 和 await 在干什么 每个名称都有意义async : 异步await: async wait简...

  • async/await

    async/await async/await 是Generator的语法糖。 Generator 通过将Gene...

网友评论

      本文标题:Promise&async/await

      本文链接:https://www.haomeiwen.com/subject/mmpqyftx.html