0

Let's say there is an NPM module that I want to require. This module is an async process, but it does not return a Promise so I cannot await on it and wait for the process to finish. Is there a way to wait for this script to finish, before continuing?

For example

// some 3rd party package
// it does not return a promise or anything
// But the function they call is async and will take time to complete
performAsyncOperation();

// In my application, I want to do
await require('the-3rd-party-package'); // <-- Wait for this to complete
Kousha
  • 32,871
  • 51
  • 172
  • 296
  • 1
    You will have to patch `performAsyncOperation` so that it returns a Promise or accepts a callback. (sounds like that package is broken if it doesn't provide such already) – CertainPerformance Jun 10 '19 at 23:03
  • 1
    Also there's `promisify` if the package does accept callbacks (if it doesn't, then it's strange and probably suspect because that's a bizarre design choice). – Pointy Jun 10 '19 at 23:05
  • @CertainPerformance this is an npm package that I would be installing; I do not/cannot patch their library. – Kousha Jun 10 '19 at 23:07
  • @CertainPerformance also don't understand why you are labeling this as a duplicate. The other question has nothing to do with my question. I want to run a script that I install via `npm` and wait for it to finish before continuing; The other link is about how to basically use a Promise. – Kousha Jun 10 '19 at 23:09
  • 1
    If the package doesn't provide any way to determine from the outside when the operation is complete, then I'd consider the package to be broken. Either raise an issue on their github, or fork it yourself and fix it, or use a horrible workaround like having a `setInterval` until you can detect that the async operation is done. (hopefully you *do* have a way to tell whether the operation is done..?) – CertainPerformance Jun 10 '19 at 23:10
  • @Kousha you didn't make it clear whether the API you're using does or does not accept at least a callback function. If it doesn't, then you're really out of luck; if it *does*, then something like `promisify` can help (if you don't want to just use the callback facility). – Pointy Jun 10 '19 at 23:15

0 Answers0