关于遍历多个接口请求问题?

每次遍历分别请求3个接口,如果第1个接口失败,后面2个接口停止执行,如果第2个接口失败,后面第3个接口停止执行,请求过程中只要失败的就把失败msg内容存进数组,最后请求完弹窗提示给用户看,现在问题是,怎么知道请求失败是最后一次呢?

import {useDispatch} from 'dva';


const dispatch = useDispatch();
const urlList = {0:'req1',0:'req2',0:'req3'};
let saveMsg = [];
async function batchReq () {
  //遍历5次,每次分别请求3个接口,如果第1接口失败,后面2个接口停止执行
  for (let i = 0; i < 5; i++) {
     await reqData('1',i);
   }
}
const reqData = (url,i) => {
   dispatch({
      type:urlList[url],
      params:{},
      onSucess: async ()=>{
          if (res&&res.code==='0') {
            //如果第1个接口失败,后面2个接口停止执行
            //如果第2个接口失败,后面1个接口停止执行
             if (url==='0') {
                 await reqData('1',i);
             }
             if (url==='1') {
                 await reqData('2',i);
             }
          } else {
             //将多次msg内容存起来,最后弹出提示
              saveMsg  = [...saveMsg ,res.msg]
              //只要接口请求code字段不是0的都会弹一次提示

             //多个接口请求失败就会提示多次,最终想要的效果是不管接口请求多少次失败,只需要弹一次提示,怎么判断最后一次请求失败的情况呢
              message.error(saveMsg.join('、');
          }
      }
    })
}
阅读 3.2k
2 个回答

把弹窗的代码独立出来,不要写在请求的方法里。

循环结束后,根据存入的数组是否有错误信息来判断是否提示

https://jsrun.net/JyPKp/edit

let saveMsg = [];

const ajax = (url,i) => {
    var p = new Promise((resolve, reject) => {
        var random = Math.round(Math.random() * 9) + 1
        setTimeout(() => {
            if (random > 5) {
                console.log(`第${i}轮循环,${url}请求成功`)
                resolve({ url, code: 0 })
            } else {
                console.log(`第${i}轮循环,${url}请求失败`)
                reject({ url, code: -1 })
            }
        }, random * 100)
    })
    return p
}
const pfn = async (i) => {
    return ajax('req1', i)
        .then(res => ajax('req2', i))
        .then(res => ajax('req3', i))
        .catch(err => {
            console.log(i, err)
            saveMsg.push({index: i, err})
        })
}

async function batchReq () {
  //遍历5次,每次分别请求3个接口,如果第1接口失败,后面2个接口停止执行
  for (let i = 0; i < 5; i++) {
     await pfn(i)     
   }
}

async function main () {
  await batchReq()
  console.log('alert', JSON.stringify(saveMsg, null, 2))
}

main()
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题