0

hi coders i have problem with this code:

const ForVideo = async data =>
  data.map(story => {
    return {
       videoUrl: story.video.versions[0].url,
       instagramId: story.pk,
       videoFilename: MediaDownloader({
       url: story.video.versions[0].url,
       dest: "/Users/Hernan/Haip/media/" + story.account.pk + "/story/"
       }),
       expiresAt: story.expiringAt,
       tappableObjects: HashMention(story),
       influencerId: story.account.pk,
       takenAt: story.takenAt,
       isVideo: true,
       videoDuration: story.video.duration,
       displayUrl: story.imageVersions2.candidates[0].url,
       imageFilename: MediaDownloader({
         url: story.imageVersions2.candidates[0].url,
         dest: "/Users/Hernan/Haip/media/" + story.account.pk + "/story/"
       }),
       callToAction: null
     };
  });

i call ForVideo (data) function that return a new JSON but the problem is that this dont return the item videoFilename andimageFilename (url from MediaDownloader() function)

how can i apply async / await or promise to get the full JSON and wait to MediaDownloader() function to finish ?

MediaDownloader() :

MediaDownloader: async options => {
let dir = options.dest;

 try {
  fs.ensureDirSync(dir);
  const { filename, image } = await download.image(options);
  return filename;
 } catch (e) {
   console.error(e);
   }
}
Hernan Humaña
  • 433
  • 5
  • 18

1 Answers1

0

try this.

 const ForVideo = data =>
  data.map(async story => {
    return {
      videoFilename: await MediaDownloader({
        url: story.video.versions[0].url,
        dest: "/Users/Hernan/Haip/media/" + story.account.pk + "/story/"
      })
    };
 });

MediaDownloader: options => {
  return new Promise((resolve, reject) => {
    let dir = options.dest;
    try {
      fs.ensureDirSync(dir);
      const { filename, image } = download.image(options);
      resolve(filename);
    } catch (e) {
      reject(e);
    }
  });
}
Diego Salguero
  • 301
  • 4
  • 7
  • 1
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! Why did you even change `MediaDownloader`, the OP's code was working fine? – Bergi Jan 21 '19 at 19:46
  • Hey man, this does not work for me, missing a async in your .map method. – Hernan Humaña Jan 21 '19 at 19:47
  • I'm sorry but I was wrong in assigning async, try it there – Diego Salguero Jan 21 '19 at 19:56