Friday, 12 May 2017

Writing to file in a promise

The function here creates a bunch of files but does not write to them. How ever, if I remove the Promise.all in the end and don't resolve the function at all it DOES write the data to the files. It doesn't matter what I try to write, I can comment out everything and just write 'hello world' and it still won't write anything. The question is simple, why?

const writeSmilFiles = (smilInfo) => {
  return new Promise ((resolve, reject) => {
    const p1 = smilPartOne();
    const p2 = smilPartTwo();

    let promises = dataTypes.new.camera_set.map(instance => {
      return new Promise((resolve, reject) => {
        const smilEntries = smilInfo.filter(smil => smil.BroadcastAndKlippTupleId == instance.BroadcastAndKlippTupleId && smil.CameraId == instance.CameraId);
        try {
          const fileName = `${__dirname}/newSmilFiles/${smilEntries[0].Smil}`;
          const file = fs.createWriteStream(fileName);
          file.write(p1);

          smilEntries.forEach(entry => {
            const smilEntry = smilSwitch(entry.Filename, entry.Bitrate, entry.Width, entry.Height);
            file.write(smilEntry);
            console.log(smilEntry);
            file.write('\n');
        });

          file.write(p2);
          file.end();
          resolve(`Smil written.`);
        } catch (ex) {
          reject(ex);
        }
      });
    });

    Promise.all(promises).then(msg => {
      resolve(msg);
    });
  });
};



via Thomas Johansen Toft

No comments:

Post a Comment