美文网首页Web前端之路
Promise.all使用场景

Promise.all使用场景

作者: 竿牍 | 来源:发表于2019-07-30 11:09 被阅读22次

问题描述:

页面挂掉了,因为接口异常导致,打开浏览器调试了一下,发现只是一个无关紧要的接口挂掉了。那么一个接口挂掉了为什么会导致整个页面无数据呢?了解Promise.all都知道,如果参数中 promise 有一个失败(rejected),此实例回调失败(reject),就不再执行then方法回调

Promise.all详情资料可查看:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Promise.all([p1, p2, p3])
  .then(res => {
    this.data1 = res[0]
    this.data2 = res[1] // 这个数据拿不到,接口挂掉了
    this.data3 = res[2]
  })
  .catch((err) => {console.error(err)})

如果参数中 promise 有一个(p2)失败(rejected),此实例回调失败(reject),就不再执行then方法回调,被catch掉了,打印了reject结果。

image.png

当然,也可以不使用Promise.all,但如果多个接口之间需要同步进行,后一个接口依赖前一个接口的返回值,这种情况做同步处理就麻烦一点了。

但是,使用Promise.all,如果有一个回调执行失败,即使其他几个promise已经进入resolved状态,then也不会执行的,或者可以说所有的promise都失败了(都不能正常取到响应结果)

正如我遇到的问题:也许可能只是一个不关键的数据加载失败,其他所有的数据也不会显示,使得项目的容错大大降低。

分析到这里,我相信大家什么时候使用Promise.all都有一些判断了,我个人认为有以下情况:几个异步操作是强相关的,后续步骤必须依赖这几个步骤全部成功才能进行。

下面是我的解决办法:

var p1 =new Promise(function(resolve,reject){
    setTimeout(function(){
        resolve(1);
    },2000)
});
var p2 = new Promise(function(resolve,reject){
          API.fetchData().then((res) => {
            resolve(res);
          }, () => {
            resolve(null); // 防止不关键的数据加载失败,影响页面显示
          })
    });
var p3 = new Promise(function(resolve,reject){
        setTimeout(function(){
            resolve(3);
        },2000)
    });
Promise.all([p1, p2, p3]).then(function (results) {
    console.log("success");
    console.log(results);
}).catch(function(r){
    console.log("err");
    console.log(r);
});

相关文章

网友评论

    本文标题:Promise.all使用场景

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