0

I am promisifying multiparty to use its form.parse. It works fine but form.parse does not return a promise whose then/catch value I can use.

var Promise = require('bluebird');
var multiparty = Promise.promisifyAll(require('multiparty'), {multiArgs:true})
var form = new multiparty.Form();
form.parse({}).then((data)=>{console.log(data)});
art
  • 226
  • 3
  • 11
  • 30
  • Instead of promify try using build-in promise to resolve and reject response. – kgangadhar May 25 '18 at 06:44
  • I would have to guess that `.parse()` is either (a) promisified as `.parseAsync()` or (b) a synchronous operation that doesn't accept a nodeback, therefore doesn't become promisified by `.promisifyAll(). Either way is shouldn't be too difficult to find out by running tests. – Roamer-1888 May 25 '18 at 07:40

2 Answers2

10

Here is my solution using build-in Promise:

const promisifyUpload = (req) => new Promise((resolve, reject) => {
    const form = new multiparty.Form();

    form.parse(req, function(err, fields, files) {
        if (err) return reject(err);

        return resolve([fields, files]);
    });
});

And usage:

const [fields, files] = await promisifyUpload(req)
serge1peshcoff
  • 4,342
  • 11
  • 45
  • 76
0

My solution for waiting until all the parts are read:

const multipartParser = new Form();
multipartParser.on('error', error => { /* do something sensible */ });

const partLatches: Latch<void, Error>[] = [];
multipartParser.on('part', async part => {
    // Latch must be created and pushed *before* any async/await activity!
    const partLatch = createLatch();
    partLatches.push(partLatch);

    const bodyPart = await readPart(part);
    // do something with the body part

    partLatch.resolve();
});

const bodyLatch = createLatch();
multipartParser.on('close', () => {
    logger.debug('Done parsing whole body');
    bodyLatch.resolve();
});

multipartParser.parse(req);
await bodyLatch;
await Promise.all(partLatches.map(latch => latch.promise));

This can be handy in cases where you want to process the parts further, for example parse and validate them, perhaps store them in a database.

ivosh
  • 153
  • 4
  • 10