多次异步请求, 处理后让数据按序

多次异步请求, 处理后让数据按序

talk is cheap, show the code!

const axios = require(axios)

// 获取数据
function getData() {
          
   
    return  new Promise((resolve ,reject)=> {
          
   
        const idList = [188, 187, 190, 191, 192, 193, 194, 189, 195, 196, 198]
        const dataList = []
        idList.map(async item => {
          
   
            const url = `https://xxxx.xxx.xxx/data?id=${
            
     item}`
            const {
          
   data: res} = await axios.get(url)
            if(res.Code !== 0) return
            dataList.push(res.Data)
            if (dataList.length === idList.length) resolve(dataList)
        })
    })
}

// 得到数据后, 进行排序
getData().then(res => {
          
   
    function add(x,y) {
          
   
        return x.CategoryID - y.CategoryID
    }
    res = res.sort(add)
    console.log(res) // 这里的数据就是根据数据中的对象里面的CategoryID升序排序后的结果。
})
经验分享 程序员 微信小程序 职场和发展