• promise


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

    • promise 有静态方法:race,all,reject,resolve, allSettled, any

    • promise原型上的方法:then,catch,finally

    • 一个 Promise 必然处于以下几种状态之一:

      • pending:初始状态,既没有被兑现,也没有被拒绝。
      • fulfilled:操作成功完成。
      • rejected:操作失败。
    • 例子1

    
    var a = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve({a: 1});
        }, 1000);
    });
    
    var b = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve({a: 1});
        }, 1200);
    });
    
    var aa = a.then((v) => {
        console.log(v, 'aa');
    });
    
    var bb = b.then((v) => {
        console.log(v, 'bb');
    });
    
    var aaa = aa.then((v) => {
        console.log(v, 'aaa');
    });
    
    var bbb = bb.then((v) => {
        console.log(v, 'bbb');
    });
    
    Promise.all([aa, bb]).then(data => {
        console.log('all', data);
    });
    
    Promise.all([a, b]).then(data => {
        console.log('a b all', data);
    });
    
    • 例子2
    var a = new Promise((resolve, reject) => {
        setTimeout(() => {
            reject({a: 1});
        }, 1000);
    });
    
    var b = new Promise((resolve, reject) => {
        setTimeout(() => {
            reject({a: 1});
        }, 1200);
    });
    
    var aa = a.then((v) => {
        console.log(v, 'aa');
    }).catch(() => {});
    
    var bb = b.then((v) => {
        console.log(v, 'bb');
    }).catch(() => {});
    
    var aaa = aa.then((v) => {
        console.log(v, 'aaa');
    })
    
    var bbb = bb.then((v) => {
        console.log(v, 'bbb');
    });
    
    Promise.all([aa, bb]).then(data => {
        console.log('all', data);
    });
    
    Promise.all([a, b]).then(data => {
        console.log('a b all', data);
    });
    
    • 例子3
    var a = new Promise((resolve, reject) => {
        setTimeout(() => {
            reject({a: 1});
        }, 1000);
    });
    
    var b = new Promise((resolve, reject) => {
        setTimeout(() => {
            reject({a: 1});
        }, 1200);
    });
    
    var aa = a.then((v) => {
        console.log(v, 'aa');
    }).catch(() => {});
    
    var bb = b.then((v) => {
        console.log(v, 'bb');
    }).catch(() => {});
    
    var aaa = aa.then((v) => {
        console.log(v, 'aaa');
    })
    
    var bbb = bb.then((v) => {
        console.log(v, 'bbb');
    });
    
    Promise.allSettled([aa, bb]).then(data => {
        console.log('all', data);
    });
    
    Promise.allSettled([a, b]).then(data => {
        console.log('a b all', data);
    });
    
  • 相关阅读:
    C 实战练习题目20 – 小球自由下落
    C 实战练习题目19
    C 实战练习题目18
    C 实战练习题目17
    C 实战练习题目16 -最大公约数和最小公倍数
    C 实战练习题目15
    C 实战练习题目14 -将一个正整数分解质因数
    C 实战练习题目13 -水仙花数
    C 实战练习题目12
    C 实战练习题目11
  • 原文地址:https://www.cnblogs.com/Running00/p/14793544.html
Copyright © 2020-2023  润新知