Caching JavaScript promise results

前端 未结 6 865
独厮守ぢ
独厮守ぢ 2021-01-03 01:55

I would make one call to the server to get a list of items. How do I make sure that only one call is made and the collections is processed only once to create a key value ma

6条回答
  •  离开以前
    2021-01-03 02:15

    Try npm dedup-async, which caches duplicated promise calls if there's a pending one, so concurrent promise calls trigger only one actual task.

    const dedupa = require('dedup-async')
    
    let evil
    let n = 0
    
    function task() {
        return new Promise((resolve, reject) => {
            if (evil)
                throw 'Duplicated concurrent call!'
            evil = true
    
            setTimeout(() => {
                console.log('Working...')
                evil = false
                resolve(n++)
            }, 100)
        })
    }
    
    function test() {
        dedupa(task)
            .then (d => console.log('Finish:', d))
            .catch(e => console.log('Error:', e))
    }
    
    test()                //Prints 'Working...', resolves 0
    test()                //No print,            resolves 0
    setTimeout(test, 200) //Prints 'Working...', resolves 1
    

提交回复
热议问题