Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I wait for asynchronous operations to complete when an Electron app is closed?

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?

like image 211
Cyril Gupta Avatar asked Oct 21 '25 04:10

Cyril Gupta


2 Answers

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!

like image 158
Norlihazmey Ghazali Avatar answered Oct 23 '25 18:10

Norlihazmey Ghazali


In my app, I do:

app.on("window-all-closed", async () => {
    await asyncThing();
    app.quit();
});
like image 23
pushkin Avatar answered Oct 23 '25 17:10

pushkin