promise

作者: 月下小酌_dbd5 | 来源:发表于2021-12-03 09:18 被阅读0次

Promise的三个重要概念及其关系:决议(resolve),完成(fulfill),拒绝(reject)

☺创建promise语法如下:
new Promise(function(resolve, reject) {});
♥Promise.prototype.catch(onRejected) 拒绝回调函数
var promise = new Promise((resolve, reject) => {
        setTimeout(() => {
            reject('failed');
        }, 0);
    });

    var promise2 = promise.catch((reason) => {
        console.log(reason);
        return 'successed';
    });
    var promise3 = promise.catch((reason) => {
        console.log(reason);
    });
    var promise4 = promise.catch((reason) => {
        console.log(reason);
        throw 'failed 2';
    });
♥结果:
image.png
♥链式调用
new Promise((resolve, reject) => {
        setTimeout(()=>{
            resolve('first success');
        },0);
    }).then((msg) => {
        //msg为'first success'
        return 'second success'; 
    }).then((msg) => {
        console.log(msg);
    });
♥结果:

第一个then返回的promise最终是'second success'
第二个then返回的promise最终是'undefined'
该程序最终返回'second success'


image.png
♥错误处理
    var promise = new Promise((resolve, reject) => {
        add(); // 抛出异常
        resolve('success'); //不执行
      });
      console.log(promise);
      promise.catch((reason) => {
        console.log(reason);
      });
♥过程:执行add抛出异常,导致promise被拒绝,拒绝原因即抛出的异常,然后在执行catch方法注册的拒绝回调
♥结果:
image.png
♥决议 完成 拒绝
   var promise = new Promise((resolve, reject) => {
        resolve(Promise.resolve('success'));
        // resolve(Promise.reject('failed'));
      });
      promise.then((msg) => {
        console.log(promise);
        console.log('完成:' + msg);
      }, (reason) => {
        console.log(promise);
        console.log('拒绝:' + reason);
      });
♥结果:
image.png
☺组合

Promise.resolve()Promise.reject() 是手动创建一个已经 resolve 或者 reject 的 Promise 快捷方法。它们有时很有用。

Promise.all()Promise.race() 是并行运行异步操作的两个组合式工具。

Promise.all([func1(), func2(), func3()])
.then(([result1, result2, result3]) => { /* use result1, result2 and result3 */ });
[func1, func2, func3].reduce((p, f) => p.then(f), Promise.resolve())
.then(result3 => { /* use result3 */ });

相关文章

网友评论

      本文标题:promise

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