I have a batch script written in JS, executed under Node.
This is a very linear, logically synchronous batch script -- Thing A has to happen before Thing B, etc. This thing needs to execute from top to bottom, ideally line by line, synchronously.
(Performance is not that important here. The execution time would be 30 seconds, worst case. Additionally, there's no UI to lock up while the code blocks. This will only ever be run in batch from the command line, and I'll probably be watching it execute every time.)
I've been working through various options:
- the "async" npm module
- writing my own Promises
- using
async
andawait
I really like the last one, just from an understandability standpoint. It "degrades" JavaScript to simple, linear execution, which is frankly what I want.
go()
async function go() {
await doThingOne()
await doThingTwo()
}
However, sometimes I have code inside my methods which comes from third-party modules, and is asynchronous with no synchronous option.
Consider:
go()
async function go() {
await doThingOne()
await doThingTwo()
}
function doThingOne() {
// do some things here
doAsyncThingFromExternalLibrary()
// do some more things here
}
How do I await
that third-party call? It's written asynchronously, has no synchronous option, and is not code that I would want to change.
Is there a way to "wrap" that call so the code stops and waits for it? Should I wrap it in my own Promise
and make it thenable
?
What's the best way to do this?