title: How to await fields before processing the file stream in multipart form
body: <p>I'm using SendGrid for receiving files via email. SendGrid parses the incoming emails and sends the files in a multipart form to an endpoint I have set up.</p>
  
  <p>I don't want the files on my local disk so I stream them straight to Amazon S3. This works perfect.</p>
  
  <p>But before I can stream to S3 I need to get hold of the destination mail address so I can work out the correct s3 folder. This is sent in a field named "to" in the form post. Unfortunately this field sometimes arrives after the files are arriving, hence I need a way to await the to-field before I'm ready to take the stream.</p>
  
  <p>I thought I could wrap the onField in a promise and await the to-field from within the onFile. But this concept seems to lock it self up when the field arrives after the file.</p>
  
  <p>I'm new to booth streams and promises. I would really appreciate if someone could tell me how to do this.</p>
  
  <p>This is the non working pseudoish code:</p>
  
  <pre><code>function sendGridUpload(req, res, next) { 
    var busboy = new Busboy({ headers: req.headers });
  
    var awaitEmailAddress = new Promise(function(resolve, reject) {
      busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
        if(fieldname === 'to') {
          resolve(val);
        } else {
          return;
        }
      });
    });
  
  
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
  
      function findInbox(emailAddress) {
        console.log('Got email address: ' + emailAddress);
  
        ..find the inbox and generate an s3Key
        return s3Key;
      }
  
      function saveFileStream(s3Key) {
        ..pipe the file directly to S3
      }
  
      awaitEmailAddress.then(findInbox)
      .then(saveFileStream)
      .catch(function(err) {
        log.error(err)
      });
    });
  
    req.pipe(busboy);
  }
  </code></pre>