promise 调用a完后再调用b

333 阅读1分钟

需求如下,C接口依赖B接口里面的数据,B接口依赖A接口里面的数据

  let url = `https://api.apiopen.top/singlePoetry`;
    //A接口
  this.$axios.get(url).then((res) => {
    setTimeout(() => {
      //模拟耗时操作
      console.log(res, "耗时返回的res");
      resolve("success");
    }, 1000);
  })
}).then(()=>{
//B接口
  return new Promise((resolve,reject)=>{  //注意该处需要返回一个Promise对象
    let url2 = `https://api.apiopen.top/getJoke?page=1&count=2&type=video`;
    this.$axios.get(url2).then((res2) => {
      console.log(res2, "res2------");
      resolve("success");
    })
  })
}).then(()=>{
//C接口
  //其他接口,此处用setTimeout模拟异步请求
  setTimeout(()=>{
    console.log('res3------')
  },100)
})

现实B异步方法需要A异步方法执行完也可以用这种

let funa = new Promise(resolve=>{
console.log("执行A方法")
resolve()
})
funa.then(()=>{
console.log("执行B方法")
})

最上面那种,如果依赖多了,是会造成回调地狱,用async,await 解决

const funa = async ()=>{
    console.log("A方法调用")
}
const funb = async ()=>{
    console.log("B方法调用")
}
const func = async ()=>{
    console.log("C方法调用")
}

const  getData = async ()=>{
   await funa ()
   await funb ()
   await func ()
}
getData()

但是有一个问题,如果这样写,其中一个有错了,就不会接着执行。

const funa = async ()=>{
    return new Promise((res,rej)=>{
        rej("在我这里出错了")
    })
    console.log("A方法调用")
}
const funb = async ()=>{
    console.log("B方法调用")
}
const func = async ()=>{
    console.log("C方法调用")
}

const  getData = async ()=>{
   await funa ()
   await funb ()
   await func ()
}
getData()

// 如果是想要A-B-C方法执行,如果其中一个出错,就跳过,接着执行下一个方法的。  
// 使用 try catch 
const funa = async () => {
    return new Promise((res, rej) => {
        rej("在我这里出错了")
    })
    console.log("A方法调用")
}
const funb = async () => {
    console.log("B方法调用")
}
const func = async () => {
    console.log("C方法调用")
}

const getData = async (tasks = []) => {
    const taskLen = tasks.length;
    let idx = 0;
            for (; idx < taskLen; idx++) {
                try{
                    const task = tasks[idx];
                    await task()
                }catch(error){
                    console.log(error + ",但是我会接着执行下去")
                    continue
                }

            }
    }
getData([funa,funb,func])