Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Created April 13, 2020 02:10
Show Gist options
  • Select an option

  • Save ericelliott/5d4220afd2bc36e5c5dccf616d3e412b to your computer and use it in GitHub Desktop.

Select an option

Save ericelliott/5d4220afd2bc36e5c5dccf616d3e412b to your computer and use it in GitHub Desktop.

Revisions

  1. ericelliott created this gist Apr 13, 2020.
    61 changes: 61 additions & 0 deletions parallel-fetch.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    // setup
    const wait = value => new Promise(resolve => {
    setTimeout(() => resolve(value), 3000);
    });

    const fetchFoo = () => wait('foo');
    const fetchBar = () => wait('bar');
    const fetchBaz = () => wait('baz');

    const fetchDataSlowly = async time => {
    // Bad. Requests run in serial waterfall.
    const foo = await fetchFoo();
    const bar = await fetchBar();
    const baz = await fetchBaz();
    return { foo, bar, baz, time: Date.now() - time };
    };

    fetchDataSlowly(Date.now())
    .then(({ foo, bar, baz, time }) => {
    console.log('fetched slowly:', foo, bar, baz, time
    );
    });


    const fetchDataQuickly = async time => {
    // Good. Fetches run in parallel.
    const [
    foo,
    bar,
    baz
    ] = await Promise.all([
    fetchFoo(),
    fetchBar(),
    fetchBaz()
    ]);
    return { foo, bar, baz, time: Date.now() - time };
    };

    fetchDataQuickly(Date.now())
    .then(({ foo, bar, baz, time}) => {
    console.log('fetched quickly:', foo, bar, baz, time);
    });


    const fetchDataQuickly2 = async time => {
    // Also good.
    const fooReady = fetchFoo();
    const barReady = fetchBar();
    const bazReady = fetchBaz();

    const foo = await fooReady;
    const bar = await barReady;
    const baz = await bazReady;
    return { foo, bar, baz, time: Date.now() - time };
    };

    fetchDataQuickly2(Date.now())
    .then(({ foo, bar, baz, time}) => {
    console.log('fetched quickly:', foo, bar, baz, time);
    });