If I understand your code correctly, you can just write:
privateProperties.setSearchedData = function(data, searchFor) {
switch (searchFor) {
case "photos":
if (!Array.isArray(data.items))
return Promise.reject("data.items is undefined or not an array");
const photoItems = data.items.map(item => item.link);
if (photoItems.some(item => !item)) {
console.error('Link is undefined');
return Promise.reject("Link is undefined");
}
return privateProperties._uiInstances['main'].uiReference
.set("photos.photoItems", photoItems);
case "videos":
return Promise.reject("videos not supported");
}
}
You are essentially trying to return the uiReference.set
promise, so just return it. There is no need to catch
a rejection from it--the rejection will be passed through for the consumer to handle. There is no need to create your own promise, and then laboriously resolve
or reject
your own new promise based on its result. Just return the promise you want. The error checking can be done up front and an explicit rejected promise returned in that case.
Using await
, this could look like the following. You can throw
instead of returning Promise.reject
. The throw
will result in the function returning a rejected promise with that as a reason.
privateProperties.setSearchedData = async function(data, searchFor) {
switch (searchFor) {
case "photos":
return privateProperties._uiInstances['main'].uiReference
.set("photos.photoItems", data.items.map(item => item.link));
case "videos":
throw new Error("videos not supported");
}
}
I've omitted the check for an array, since a non-array will cause the .map
to fail, which will result in the entire function returning a promise rejected for some reason such as "Cannot read property map
of null".
I've also assumed a redesign of uiReference.set
to do the check for missing or null links, and reject if that happens, so we don't have to check that the links are all there either. When all is said and done, this function really needs to do nothing more than switch on searchFor
, extract the links from the data items, and then call and return uiReference.set
. Personally, I would prefer to have separate functions for searching photos and videos, in which case it becomes very clean:
privateProperties.setSearchedPhotosData = async function(data) {
return privateProperties._uiInstances['main'].uiReference
.set("photos.photoItems", data.items.map(item => item.link));
}
The only remaining purpose of the async
is to turn a failure of map
(when data.items
is not an array) into a rejected promise. However, if this situation represents a coding error, rather than a semi-expectable situation that you want to handle, it might be better to just let it throw (by removing async
).