K
K
Kirill2022-03-26 01:43:14
JavaScript
Kirill, 2022-03-26 01:43:14

How to make an abortController of the desired request on an event in an array of requests?

I send several files with download progress and the ability to cancel each one by a button.

for understanding, visually looks like this

623e42a91e184886913270.png


in the sendFiles method, I go through the array of files and create a config for the request, including adding abortController and filling the array of controllers in data:
sendFiles

async sendFiles() {
            const vue = this;
            for (let i = 0; i < vue.inputFiles.length; i++) {
                if (!vue.inputFiles[i].success && !vue.inputFiles[i].error) {
                    const controller = new AbortController();
                    const config = {
                        baseURL: '/api',
                        signal: controller.signal,
                        onUploadProgress: function (e) {
                            vue.inputFiles.splice(i, 1, { ...vue.inputFiles[i], progress: Math.round((e.loaded * 100) / e.total) });
                        },
                    };
                    this.abortControllers.push(controller);
                    setTimeout(() => controller.abort(), 1000)

                    const data = convertToFormData({ file: vue.inputFiles[i].file });
                    await this.sendFile(data, config, i);
                }
            }
        }



sendFile method - separate request for each file
sendFile

async sendFile(data, config, index) {
            const vue = this;
            httpClient
                .post(this.urlAdd, data, config)
                .then((res) => {
                    vue.inputFiles[index].status = 'success';
                    vue.inputFiles[index].id = res.data.file.id;
                    vue.$emit('fileAdded', res.data)
                })
                .catch((err) => {
                    vue.inputFiles[index].status = 'error';
                    vue.inputFiles[index].error = err;
                })
        },



On button click I try to do something like this.abortControllers[index].abort(), but it doesn't work. Also, in the sendFiles method, you can notice setTimeout per second in the code, and it doesn’t tritely interrupt the request either.

Why is my implementation not working and how can I fix it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kirill, 2022-03-30
@Lirrr

As a result, I did according to this article https://coderethinked.com/how-to-cancel-a-request-... , only created a cancel method inside the request creation cycle and added these methods to the { fileID: cancelMethod } format object so that from anywhere you can then use them.

P
postya, 2022-03-29
@postya

see this thread
https://stackoverflow.com/questions/6907096/stop-r...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question