I have the following JS function that fetches data and put in a window.data
property:
function fetchData() {
if (window.data) {
return Promise.resolve(window.data)
} else {
return fetch('http://example.com/data.js')
.then(response => response.json())
.then(json => window.data = json)
}
}
The code works fine.
However, when there are two concurrent calls to that function, the first call to fetchData
will fire the fetch
.
Because the fetch
can take some time, a second call to fetchData
won't find anything in the window.data
and fire the same fetch
.
Question :
How can I send an elegant pending
signal to the second call and return the result as a resolved promise ?
Unless a promise-based solution is not possible, is there any another approach I can dig ?
The ideal solution should not block the second block but instead deal with it asynchronously with promises
Regards
I tried a mutex-based solution but it seemed over complicated.