重复请求合并

异步不可怕“死记硬背”+ 实践拿下(上) | 前端进阶 (mbear.top)

假设现在后端有一个服务,支持批量返回书籍信息,它接受一个数组作为请求数据,数组储存了需要获取书目信息的书目 id,这个服务 fetchBooksInfo 大概是这个样子:

const fetchBooksInfo = bookIdList => {
    // ...
    return ([{

            id: 123,
            // ...

        },
        {
            id: 456
            // ...
        },
        // ...
    ])
}
fetchBooksInfo 已经给出, 但是这个接口最多只支持 100 个 id 的查询。

现在需要开发者实现 getBooksInfo 方法,该方法:

支持调用单个书目信息:

getBooksInfo(123).then(data => {console.log(data.id)}) // 123
短时间(100 毫秒)内多次连续调用, 只发送一个请求 ,且获得各个书目信息:


getBooksInfo(123).then(data => {console.log(data.id)}) // 123
getBooksInfo(456).then(data => {console.log(data.id)}) // 456
注意这里必须只发送一个请求,也就是说调用了一次 fetchBooksInfo。
const bookIdListToFetch = []
const promiseMap  = {}

const getUniqueArray =array = >Array.from(new Set(array))
let timr 
const getBookInfo = bookId => new Promise((resolve,reject)=>{
promiseMap[bookId] = promiseMap[bookId]||[]
promiseMap[bookId].push({resolve,reject})
})
const clearTask = () =>{
	bookIdListToFetch  = []
	promiseMao = {}
}
if(bookIdListToFetch.length===0){
	bookIdListToFetch.push(bookId)
	timer = setTimeout(()=>{
	handleFetch(bookIdListToFetch,promiseMap)
	clearTask()
	},100)
}else{
	bookIdListToFetch.push(bookId)
    bookIdlistToFetch = getUniqueArray(bookIdListoFetch)
    if(bookIdListToFetch.length>=100){
        clearTimeout(timer)
        handleFetch(bookIdListFetch,promiseMap)
        clearTask()
    }
}
const handleFetch = (list, map) => {
    fetchBooksInfo(list).then(resultArray => {
        const resultIdArray = resultArray.map(item => item.id)

        // 处理存在的 bookId
        resultArray.forEach(data => promiseMap[data.id].forEach(item => {
            item.resolve(data)
        }))

        // 处理失败没拿到的 bookId
        let rejectIdArray = []
        bookIdListToFetch.forEach(id => {
            // 返回的数组中,不含有某项 bookId,表示请求失败
            if (!resultIdArray.includes(id)) {
                rejectIdArray.push(id)
            }
        })

        // 对请求失败的数组进行 reject
        rejectIdArray.forEach(id => promiseMap[id].forEach(item => {
            item.reject()
        }))
    }, error => {
        console.log(error)
    })
}

最后更新于

这有帮助吗?