Created
December 26, 2019 05:03
-
-
Save lvnam96/313ada9fbbced21fceb517780ee7ef86 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function workAfterDataRetrieved (data) { | |
return new Promise((resolve) => { | |
// doSomeDutyTaskHere(); | |
console.log('task done: ' + data.name); | |
resolve(); | |
}); | |
} | |
function getJSON (url) { | |
console.log('sent: ' + url); | |
return fetch(url).then((response) => { | |
console.log('received: ' + url); | |
return response.json(); | |
}); | |
} | |
window.addEventListener('WebComponentsReady', function() { | |
getJSON('/api/some.json') | |
.then(function(response) { | |
var sequence = Promise.resolve(); | |
// .map executes all of the network requests immediately, because Promise (fetch in getJSON) is executed immediately | |
var arrayOfExecutingPromises = response.results.map((url) => getJSON(url)); | |
arrayOfExecutingPromises.forEach((request) => { | |
// Loop through the pending requests that were returned by .map (and are in order) and turn them into a sequence. | |
// request is a getJSON() that's currently executing. | |
sequence = sequence.then(() => { | |
// Remember that createPlanetThumb is a Promise, so it must resolve before Promises later in the sequence can execute. | |
return request.then(workAfterDataRetrieved);// doTaskInSequenceAsSoonAsItsNeededDataIsLoaded | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment