I've been using promises + async/await for some time now, I thought I was comfortable with them, but this situation really has me stumped. Any advice/guidance is greatly appreciated!
Context: My app is making URI requests, but I have to delay each request by a couple seconds. To make the delay more exact, I set up a queue for making the requests. No problem using callbacks, but I've been at it for a while, and I can't seem to wrap my head around how to pull it off using promises.
Sandboxed the callback code below:
const queue = []
let t;
function addToQueue(params, cb) {
queue.push({params,cb})
_run()
}
function _run() {
if (!t && queue.length) {
const {params,cb} = queue.shift()
_dummyFetch(params).then( data => cb(data) )
_startTimer()
}
}
function _startTimer() {
t = setTimeout( _endTimer, 2000 )
}
function _endTimer() {
t = null
_run()
}
async function _dummyFetch() {}
Sandbox debug:
function seconds() { return Math.round(new Date().getTime()/1000) }
function log(t) { console.log(t + " " + seconds()) }
function logFn(t) { return () => log(t) }
log("init")
addToQueue({}, logFn("request 1")) // should be close/same as init time
addToQueue({}, logFn("request 2"))
addToQueue({}, logFn("request 3"))
// If I could figure out how to make it a promise:
// addToQueue( ... ).then( data => ... )