Я нажимаю на конечную точку REST несколькими клавишами. Я хочу попробовать ключи, пока один из них не вернет объект. Я сделал это двумя способами, но чувствую себя действительно неудовлетворенным. Должен ли я использовать цепочку обещаний?
Способ первый, попробуйте поймать руководство
class MyRESTAPI extends RESTDataSource { // this comes from apollo server
async getEndPoint(potentialkeyobject) {
const id1 = potentialkeyobject.id1;
const id2 = potentialkeyobject.id2;
let response = [];
try {
// this.get returns a promise
response = await this.get(`historical/${id1}?lastdays=all`);
} catch (err) {
// sometimes it can return 404
console.error('trying iso3, failed, trying _id2');
try {
// try other key
response = await this.get(`historical/${id2}`);
} catch (err) {
// if nothing worked, return empty array
console.error('error with _id', countryInfo);
return response;
}
}
// ...Do other stuff with responsse
return response
}
}
Как я могу настроить это с N количеством клавиш, чтобы попробовать? Я пытался использовать for-of l oop, ниже
Метод 2 - для l oop
В этом методе я должен проверить, является ли объект пустым. Это кажется супер неуклюжим.
class MyRESTAPI extends RESTDataSource { // this comes from apollo server
async getEndPoint(potentialkeyobject) {
///Lots of ids to try
const potentialIds = [
countryInfo._id,
countryInfo.iso3,
countryInfo.iso2,
];
//start with an empty object
let response = Object();
for (const index of potentialIds) {
console.log(index);
try {
//if we get response, lets break
response = await this.get(`historical/${index}?lastdays=all`);
break;
} catch (err) {
console.log(err);
}
}
//if object is empty, return an array instead
if (Object.keys(response).length===0) {
return [];
}
//do other stuff with response
return response
}
}
Любой совет о том, как сделать это с помощью функций более высокого уровня или цепочки обещаний, был бы признателен.