Skip to content

Instantly share code, notes, and snippets.

@mandemeskel
Created November 19, 2021 09:24
Show Gist options
  • Save mandemeskel/3f759fa8029d79eae5bb60dbe25a79ff to your computer and use it in GitHub Desktop.
Save mandemeskel/3f759fa8029d79eae5bb60dbe25a79ff to your computer and use it in GitHub Desktop.
Using Axios' Cancel Token with Electron's IPC
// Cancel Token Docs: https://axios-http.com/docs/cancellation
// IPC Docs: https://www.electronjs.org/docs/api/ipc-main
import { ipcMain } from ‘electron’
import axios from 'axios'
const CancelToken = axios.CancelToken
let cancel
// 1. make the request
ipcMain.handle('download', async (event, ...args) => {
console.log('main: download', event, args)
const result = await axios.get(
'https://api.com/download',
{
file: args[0],
cancelToken: new CancelToken(function executor(cancelor) {
// 2. get the cancel token
cancel = cancelor
})
},
)
return result.data
})
// 3. listen for cancellation events
ipcMain.handle('cancel-download', async (event, ...args) => {
console.log('main: cancel-download', event, args)
// 4. make sure cancel is defined and cancel the equest
if (cancel) cancel.cancel()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment