Xiuer Old
Oct 17, 2024

--

Thanks for sharing, is that how it works?

function cancelableOperation(signal) {

return new Promise((resolve, reject) => {

// Simulate a long-running asynchronous operation

const timer = setTimeout(() => {

resolve('Operation completed');

}, 5000);

// If abort signal is received, cancel the timer and reject the Promise

signal.addEventListener('abort', () => {

clearTimeout(timer);

reject(new Error('Operation was cancelled'));

});

});

}

// Create an AbortController instance

const controller = new AbortController();

const signal = controller.signal;

// Start the asynchronous operation

cancelableOperation(signal)

.then(result => console.log(result))

.catch(error => console.error(error.message));

// Cancel the operation at some point

setTimeout(() => {

controller.abort();

}, 2000);

--

--

Xiuer Old
Xiuer Old

Written by Xiuer Old

🔥Little brother teaches front-end and AI online🌈

No responses yet