How to Chain two Fetches Together

I am retrieving two JSON files, DefMenu.json, and customMenuTest.json, processing the data, and then using them to generate menus though a function called generateMenu.

This calls the first file, waits for the data to be returned and processed, writes it to local storage, and invokes the menu generation code.

fetch(defMenuURL)
    .then(function(response) {
        return response.json();
    })
    .then(function(defaultMenu) {
        defMenu = defaultMenu; //create variable with global scope
		localStorage.setItem('defaultMenu',JSON.stringify(defMenu));
		generateMenu();
	})

How do I fetch the second file, and then ensure that this promise is completed, before invoking generateMenu?

//in async function
var firstJson = await fetch(firstURL);
var secondJson = await fetch(secondURL);
generateMenu(firstJson, secondJson)

or http://documentup.com/kriskowal/q/
Q.all([firstFetch, secondFetch]).then(generateMenu)

You don’t need Q, you can just do

Promise.all([ firstFetch(), secondFetch() ]).then(generateMenu);

if you want to wait for both promises. The difference between using Promise.all and two awaits is when the actual HTTP requests are sent.

1 Like

Thanks.

This will allow me incorporate both the standard and custom menus into the same function, and so use only one listener for changes to local storage.

See my question on that here.