#Make a function that will run syncronously even if called in multiple async functions

16 messages · Page 1 of 1 (latest)

mild escarp
#

The title is confusing. Here's the problem I'm trying to solve

I have a sorted array of numbers. The numbers represent unix timestamps

let timeIndex = [2, 6, 10, 67, 300, 800000]

I want to put a new time in that array

let addTime = (time: number) => {
  let index = getIndex(timeIndex, time)
  timeIdx.splice(index, 0, time)
}

The thing is though, I'm running ^this function^ inside of a callback, and that callback doesnt wait until the previous one is finished

database.listenFor('posts').whenFound(post => {
  addTime(post.time)
})

This will cause errors, because the function addTime will run parallel with itself, and that'll screw with the indexes
Assume there's no way to change the behaviour of whenFound, and waiting for all the posts isnt an option. how do I make addTime run syncronously?

golden sky
#

You can not escape async.
You could try using a queue. When adding a new time, it is instead enqueued. While there are entries in your queue, call addTime with the popped entry

mild escarp
#
//          post    time
let queue: [string, number][] = []
let running = false

function addTime(post:string, time:number) {
  if (running) {
    queue.push({post, time})
    return
  }
  running = true
  let index = getIndex(timeIndex, time)
  timeIdx.splice(index, 0, time)
  if (queue) {
    let next = queue.shift()
    addTime(...next)
  }
  running = false
}
#

something tells me this will break

#

It takes a computer a millionth of a second to change a variable from true to false. If it gets in during that fraction of a second its going to run two at the same time anyways

golden sky
#

JS runs single threaded by default. The function is therefore run to completion before the dispatcher calls the handler again

mild escarp
elder kayak
#

An array is also always truthy, you may want queue.length instead

mild escarp
elder kayak
#

No. As said, the function is run to completion. If the if is not entered, the very next instruction the program will execute is switching running

mild escarp
#

alright

#

this seems really hard to write tests for so I just gotta pray you're right

#

ty