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

764 Views Asked by At

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?

3

There are 3 best solutions below

4
Mustafa Demiraslan On

You can use before-quit event in main process(main.js):

function task1() {
  return new Promise((resolve) => {
    // do something
    resolve("task1");
  });
}

function task2() {
  return new Promise((resolve) => {
    // do something
    resolve("task2");
  });
}

app.on('before-quit', function () {
  task1().then((_resp1) => {
    task2().then((_resp2) => {
      app.quit();
    });
  })
})
0
pushkin On

In my app, I do:

app.on("window-all-closed", async () => {
    await asyncThing();
    app.quit();
});
0
Norlihazmey Ghazali On

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!