You don't need a lot of what you have in your question or your answer. You can just do this:
const url1 = "http://fakeapi.com/getData1";
const url2 = "http://fakeapi.com/getData2";
return Promise.all([
fetch(url1).then(res => res.json()).then(data1SpecificAction),
fetch(url2).then(res => res.json())
]).then([data1, data2] => {
if (data1 && data2) return; // resolve
// reject with appropriate error
let msg = data1 ? "missing data2" : "missing data1";
throw new Error(msg);
});
Things you do not need to do in your question and your answer:
- Don't wrap existing promises in another manually created promise. That is considered an anti-pattern as the manually created promise is simply not needed. You can just return the promises you already have.
- Don't assign a
.then()
result to a higher scoped variable. Though there are occasionally reasons for this, this is not one of them and is usually a warning sign that you're doing things wrong.
There are some annoyances about the fetch()
interface that I find often benefit from a helper function (such as a 404 status resolves, not rejects):
function fetchJson(...args) {
return fetch(...args).then(res => {
if (!res.ok) throw new Error(`Got ${res.status} status`);
return res.json();
});
}
const url1 = "http://fakeapi.com/getData1";
const url2 = "http://fakeapi.com/getData2";
return Promise.all([
fetchJson(url1).then(data1SpecificAction),
fetchJson(url2)
]).then([data1, data2] => {
if (data1 && data2) return; // resolve
// reject with appropriate error
let msg = data1 ? "missing data2" : "missing data1";
throw new Error(msg);
});
And, in your specific case where you want to reject if the result is falsey, you could even do this:
function fetchJsonCheck(...args) {
return fetch(...args).then(res => {
if (!res.ok) throw new Error(`Got ${res.status} status`);
return res.json();
}).then(result => {
if (!result) throw new Error("empty result");
return result;
});
}
const url1 = "http://fakeapi.com/getData1";
const url2 = "http://fakeapi.com/getData2";
return Promise.all([
fetchJsonCheck(url1).then(data1SpecificAction),
fetchJsonCheck(url2)
]);