Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

ju5t
ju5t
961 Points

Promises and multiple calls

I'm working on a project that connects to a message queue. Once it receives a message it has to run the following steps in sequence (for a single task):

  1. Connect to a database and retrieve the row for its task;
  2. Download a file from any storage (local or s3);
  3. Extract the file into a temporary location;
  4. Run analysis on the contents of that file;
  5. Generate images and store them (local or s3);
  6. Update the database.

This turned out to be a major challenge for a Javascript newbie. All those asynchronous calls are mind blowing. I have no problem with all the individual tasks but I can't get them to run in the right sequence. I'm struggling how to fit this into Promises.

I've done the course on both the basics of NodeJS and the one that explains Promises but what I find most difficult is the fact that each step in this sequence has it's own asynchronous call. I find that I'm quickly building my own version of a pyramid of doom.

I can't share all code but I've added a gist on GitHub: https://gist.github.com/ju5t/2ee007af55c3dc8b235f3839ec4c2dac

  • database.query returns a Promise.
  • files.get returns a fs.createReadStream

I expected to see:

Extraction done
Inspection {
  id: '2ce8a281-3354-4f67-b41a-b0d8d2466c6b'
etc.

Instead I get:

$ node index.js
undefined
Extraction done

Who can guide this poor Python-developer in the right direction?

1 Answer

ju5t
ju5t
961 Points

I think I found the solution myself. In the example I rewrote

.then(inspection => {
  files.get(`${inspection.id}.zip`)
       .pipe(unzip.Extract({path: `tmp/${inspection.id}/`}))
       .on('close', () => {
          console.log('Extraction done');
          return inspection;
        });
})

into

.then(inspection => {
  return new Promise((resolve, reject) => {
    var file = files.get(`${inspection.id}.zip`);
    file.pipe(unzip.Extract({path: `tmp/${inspection.id}/`}))
    file.on('close', () => {
      console.log('Extraction done');
      resolve(inspection)
    })
  });
})