0

First of all I apologize for asking question about async/await, as I know there are lots of answers, however after reading many of them, I have not come to a working solution.

There is a search function flickr.js which searches Flickr API for a query, but that function returns Promise, but I need an object {query, images : [{photo1}, {photo2}, {photo3}]}

flickr.js function

window.MODULES.Flickr = async query => {
const opts = {
api_key: 'API_KEY'
};
const photos = await window.fetch(
`https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${
  opts.api_key
}&text=${query}&format=json&nojsoncallback=1
`
);
const data = await photos.json();
const pictures = data.photos.photo;
const images = [];

pictures.forEach(picture => {
return images.push({
  id: picture.id,
  url: `https://farm${picture.farm}.staticflickr.com/${picture.server}/${
    picture.id
  }_${picture.secret}_s.jpg`,
  title: picture.title
});
});

return {
  query,
  images
 };
};

and it is called from

ImageFinder.js

function() {
let ImageFinder = (window.CLASSES.ImageFinder = function() {});

 ImageFinder.prototype.search = (query, moduleId) => {
  switch (moduleId) {
   case 'static':
     return window.MODULES.Static(query);
   case 'flickr':
     return window.MODULES.Flickr(query); // Need to return object { query, images : [{photo1}, {photo2}, {photo3}] }

   default:
    throw Error('Search module not found.');
  }
 };
});
Donatas
  • 25
  • 1
  • 4

2 Answers2

1

Your window.MODULES.Flickr(query); returns a promise and the only way you can deal with the result of that promise { query, images } is by resolving the promise. There is no other way around this.

Hence if you want to use the promise result in ImageFinder.prototype.search then you could mark it as async and use await window.MODULES.Flickr(query); in inside your search function to resolve the value.

Moreover, all functions using ImageFinder.prototype.search will also necessarily have to resolve the promise first e.g. using await or then()

var obj = await imageFinder.search(query, moduleId);
Felix K.
  • 14,171
  • 9
  • 58
  • 72
0

An async function is an ES7 wrapper for a promise. It is simply a way of expressing the same thing. In order to receive the returned value from the function, it needs to be waited for because it is asynchronous. This would be achieved by using a parent function that is also asynchronous. So let's say I have 2 functions, a and b. They are both asynchronous.

async function a () {
    console.log(await b() );
}

When called, a will print the returned value of b. When an error occurs or the function is returned, the promise is 'resolved' or 'rejected' respectively.

A promise returns its value as a regular function would, with the difference that in order to capture this result, it needs to be waited for, or using specific promise functions like then or catch.

Hope this helps

J-Cake
  • 1,526
  • 1
  • 15
  • 35