Promisifying multiparty

1.7k views Asked by At

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)});
2

There are 2 answers

0
ivosh On

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.

0
serge1peshcoff On

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)