I have an Electron JS desktop application that is supposed to do some closing operations when it's closed or quit. However, the app is closing before my asynchronous operations are ended.
How can I make the app wait for the asynchronous options to complete and close only when they are done?
Facing this issue and here is the code to handle async call before application quit (at least works for me):
Subscribe to before-quit event:
let flaqQuit = false;
app.on('before-quit', async function(event) {
console.log('before-quit event triggered')
if (!flagQuit) {
// call this line to stop default behaviour occur
// (which is terminating the application)
event.preventDefault();
await callAsynchronousLogicHere();
// Programmatically quit the application as previously
// we stop the quit behaviour
app.quit();
// Mark the variable to true, then later when
// quit it no longer entering this block of code
flagQuit = true;
}
});
As you can see, i use flagQuit variable to decide whether the code should enter if block for the 2nd call of app.quit().
before-quit event will trigger when you press CMD + Q or call app.quit(), so this event will trigger twice and the flagQuit variable will handle this lifecycle for us.
Make sure to use flaqQuit otherwise this code will lead to infinite loop!
In my app, I do:
app.on("window-all-closed", async () => {
await asyncThing();
app.quit();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With