Promise

一 概述

Promise(承诺)有三种状态:pending(待定的)、fulfilled(履行)、reject(拒绝)。

二 创建Promise

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    </head>
    <body>
        <script>
            let obj = axios.get('/abc');
            console.log(obj); // Promise {<pending>}
            console.log(obj instanceof Promise); // true;
        </script>
    </body>
</html>

三 执行Promise

then方法接受两个函数作为参数。onFulfilled是必须的,onRejected是可选的。

axios.get('/user?ID=12345')
    .then(val => {
        console.log('fulfill函数', val);
    }, reason => {
        console.log('reject函数', reason);
    });     

四 捕获异常

(1)Promise拒绝时,如果onRejected是个函数,则执行onRejected函数。

axios.get('/user?ID=12345')
    .then(val => {
        console.log('fulfill函数', val);
    }, reason => {
        console.log('reject函数', reason);
    })
    .catch(err => {
        console.log(err);
    });

(2)如果onRejected不是函数或者为空,则JS引擎内部会提供一个函数来作为onRejected函数,并且这个替代函数会抛出错误,从而执行catch部分。

axios.get('/user?ID=12345')
    .then(val => {
        console.log('fulfill函数', val);
    })
    .catch(err => {
        console.log('出错了',err);
    });

五 返回值

then、catch的返回值都是Promise对象,所以可以进行链式调用。

let obj = axios.get('/user?ID=12345')
    .then(val => {
        console.log('fulfill函数', val);
    },reason => {
        console.log('reject', reason);
    });
setTimeout(()=>{
    console.log(obj);
},1000);

let obj = axios.get('/user?ID=12345')
    .then(val => {
        console.log('fulfill函数', val);
    })
    .catch(err => {
        console.log('出错了',err);
    });
setTimeout(()=>{
    console.log(obj);
},1000);

原文地址:https://www.cnblogs.com/sea-breeze/p/10488327.html