QuickAnswer
by

JavaScriptで複数のJSONを非同期で読み込み

JavaScriptで複数のJSONを非同期で読み込み

IE(Internet Explore)が消滅して当たり前にモダンJavaScriptつまりES2015,ES2017,ES2022が使用できる環境が整った。

JavaScriptで複数のJSONを読み込むコードを書いてみた。

class Fetches {
    'use strict';
    #_responseObjs;
    //@param array urls [path1] | [path1,path2] | ...
    jsonObjs(urls) {
        return new Promise((resolve) => {
            (async () => {
                try {
                    const fetchUrlPromises = urls.map(
                        url => fetch(url,{method:'GET'})
                            .then(response => {
                                if (response.ok) {
                                    return response.json();
                                }
                                throw new Error('Network response was not ok');
                            })
                    );
                    this.#_responseObjs = await Promise.all(fetchUrlPromises);
                    resolve();
                } catch (error) {
                    console.error(error);
                }
            })();
        }).then(() => {
            return this.#_responseObjs;    //urlsと同じ数の配列が返る [objs1] | [objs1,objs2] | ...
        });
    }
}

const _path1 = 'path/to/a1.json';
const _path2 = 'path/to/a2.json';
const _path3 = 'path/to/a3.json';
let _obj1;
let _obj2;
let _obj3;
(new Fetches()).jsonObjs([_path1,_path2,_path3])
    .then((res) => {
        [_obj1,_obj2,_obj3] = res;
        render();
    });

function render() {
    //次の処理
}

_path1のJSONは _obj1 として読み込まれる。
_path2のJSONは _obj2 として読み込まれる。
_path3のJSONは _obj3 として読み込まれる。

CONTENTS