Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pilfer node-fetch timeout into the Fetch API #617

Closed
JSONRice opened this issue Apr 11, 2018 · 2 comments
Closed

Pilfer node-fetch timeout into the Fetch API #617

JSONRice opened this issue Apr 11, 2018 · 2 comments

Comments

@JSONRice
Copy link

JSONRice commented Apr 11, 2018

Earlier I posted on #175 Then the thread was locked and marked as resolved. I just wanted the opportunity to update my response to #175 and propose that the timeout from node-fetch be integrated directly into the Fetch API. When I first uploaded my AjaxService from #175 I failed to realize that the node-fetch library I was using already had support for timeout, so here is the updated code. This seems to work well so if anyone really needs a timeout I would highly recommend looking into node-fetch rather than the ES6 Fetch API.

node-fetch features: https://github.com/bitinn/node-fetch#features

The updated service:

/************************************************
 * Asynchronous functions with async and await.
 ***********************************************/
"use strict";
const fetch = require('node-fetch');
// Lots of data (130Mb):
let TARGET_URL = "https://raw.githubusercontent.com/zemirco/sf-city-lots-json/master/citylots.json";

class AjaxService {
    constructor() {
        this._timeout = {active: false, ms: 0};
    }

    set timeout(timeout) {
	    this._timeout = JSON.parse(JSON.stringify(timeout)); // deep copy
    }

    resetTimeout() {
        this.timeout = {active: false, ms: 0};
    }

    /***
     * Asynchronous fetch decorator.
     *
     * @param url to target
     * @param options should
     * @returns {Promise.<*>}
     */
    async asyncFetch(url, options = {
        cache: 'default',
        credentials: 'omit',
        headers: {
            'content-type': 'application/json'
        },
        method: 'GET',
        mode: 'same-origin',
        redirect: 'manual',
        referrer: 'client',
        timeout: 0
    }) {
        if (this._timeout.active && this._timeout.ms > 0) {
            options.timeout = this._timeout.ms;
            let msg = (options.timeout >= 1000) ? `${options.timeout/1000} second(s)` : `${options.timeout} millisecond(s)`;
            console.log(`timeout set to ${msg}`);
        }

        let response = await fetch(url, options);

        if (response.ok) {
    	    return await response.json();
        } else {
            throw new Error(response.status);
        }
    };

    // Run the data fetch function.
    fetch(url, options) {
        this.asyncFetch(url, options)
   	  .then(data => console.log("Acquired fetched data: ", data.type))
	  .catch(reason => console.error("Caught error: ", reason.message));
    };
}

let ajaxService = new AjaxService();

// Demo the service:
ajaxService.fetch(TARGET_URL);

// This should run first since it's a bogus url and the response is faster:
ajaxService.fetch(TARGET_URL + "bogus");

// Test the timeout of the initiating request by making a very fast request that should timeout:
ajaxService.timeout = {active: true, ms: 1000};
ajaxService.fetch(TARGET_URL);

ajaxService.resetTimeout();
@dgraham
Copy link
Contributor

dgraham commented Apr 11, 2018

propose that the timeout from node-fetch be integrated directly into the Fetch API

The right place to do this is linked from #175 (comment). This repository contains a JS implementation of the Fetch API, but we don't control what goes into the standard API.

@ianstormtaylor
Copy link

FWIW, I've opened an issue whatwg/fetch#951 with a proposal for a timeout option that solves 90% of use cases, in case anyone's interested. I think it's super important to add to make sure calls to fetch (or res.json()) don't hang indefinitely.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Oct 1, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants