es5与es6的promise分别实现等待多个接口返回数据执行相应操作(4399笔试)

场景:有时候我们同时需要两个接口返回的数据才能实现进一步操作,下面介绍2种方法
方法1:利用js回调嵌套的方式

//  异步接口1:返回当天在线用户数
function getOnlinePerson(callback){
    //模拟实现
    var onlinePerson = Math.ceil(Math.random()*1000)
    setTimeout(function(){
        callback(onlinePerson)
    },Math.random()*1000)
}

//异步接口2:返回当天总注册用户数
function getRegPerson(callback){
    //模拟实现
    var RegPerson = Math.ceil(Math.random()*1000)+1000
    setTimeout(function(){
        callback(RegPerson)
    },Math.random()*1000)
}

//异步接口,返回当天在线人数比,需要前两个接口的数据
function calOnlinePercent(onlinePerson,RegPerson,callback){
    //模拟实现
    var percent = Math.ceil(onlinePerson/RegPerson*100)
    setTimeout(function(){
        callback(percent)
    },Math.random()*1000)
}

为了实现嵌套调用,另外定义一个函数,total,保证接口返回数据成功后执行打印百分比操作
实现如下:

function total(){
  getOnlinePerson(function(onlinePerson){
       getRegPerson(function(RegPerson){
            calOnlinePercent(onlinePerson,RegPerson,function(percent){
                  console.log(percent)  //此处执行操作,打印最后结果
        })
    })
})
}

方法2:利用es6的promise解决回调地狱问题
每个异步接口 返回一个promise对象

function getOnlinePerson(){
    //模拟
    return new Promise(function(resolve,reject){
        var onlinePerson = Math.ceil(Math.random()*1000)
        setTimeout(function(){
            resolve(onlinePerson)
        },Math.random()*1000)
    })
   
}
function getRegPerson(){
    //模拟
    return new Promise(function(resolve,reject){
            var RegPerson = Math.ceil(Math.random()*1000)+1000
            setTimeout(function(){
                resolve(RegPerson)
            },Math.random()*1000)
            })
  
}

function calOnlinePercent(onlinePerson,RegPerson){
    return new Promise(function(resolve,reject){ 
        var percent = Math.ceil(onlinePerson/RegPerson*100)
        setTimeout(function(){
            resolve(percent)
        },Math.random()*1000)
    })
}

利用promisee.all方法保证接口数据成功返回再执行操作

Promise.all([getOnlinePerson(),getRegPerson()]).then(function([onlinePerson,RegPerson]){
    //这里写等这两个ajax都成功返回数据才执行的业务逻辑
     calOnlinePercent(onlinePerson,RegPerson).then(function(percent){
        console.log(percent)
     })
})

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容