Construct a timeout cancelled ajax through koa2 and Promise.race().

MDN said:

You can use the AbortController.AbortController() constructor to create a new AbortController object. Use the AbortSignal object to communicate with the DOM request.

There is a high requirement for browser compatibility. chrome is over 66 and firefox is over 57. Because of this requirement, the traditional XHR is used to implement this function.

The server uses koa2:

/**
 * @vividw
 * 2019.1.10
 */
const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const router = new Router();
const { resolve } = require('path');
const koaStatic = require('koa-static');
const cors = require('@koa/cors');

const sleep = (count) => new Promise(resolve => {
    setTimeout(resolve, count);
});

// router.get('/', async (ctx, next) => {
//     ctx.body = 'Hello,Wolrd!';
//
//     await next();
// });

router.get('/data', async (ctx, next) => {
    await sleep(3000);
    ctx.body = {
        data: '12345'
    }

    await next();
});

app
    .use(cors())
    .use(koaStatic(resolve(__dirname + '/')))
    .use(router.routes())
    .use(router.allowedMethods());

app.listen(3000, () => {
    console.log('App running!');
});

The important point is that setTimeout (CTX. Body ='12345 ', 3000) cannot be used directly; in this way, an error will be reported directly back to the front end.

Front end code:

 const ownFetch = (count) => new Promise((resolve,reject) => {
            const xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    if(xhr.status == 200){
                        resolve(xhr);
                    }
                 }
            }
            xhr.timeout = count;
            xhr.open('get', 'http://localhost:3000/data', true);
            xhr.send();
        })
        window.onload = () => {
            const timeout = (count) => new Promise((resolve, reject) => {
                setTimeout(() => {
                    reject('failed');
                }, count);
            });
            (async () => {
                ownFetch(2000);
            })();
        }

Note that the third parameter of xhr.open() is set to true to set the AJAX request to asynchronous, and then because timeout will cancel the request, xhr.abort() is not needed to cancel the request explicitly

Keywords: Front-end Firefox

Added by opels on Sun, 08 Dec 2019 17:28:45 +0200