0

我承诺多方使用它的 form.parse。它工作正常,但 form.parse 不返回我可以使用其 then/catch 值的承诺。

var Promise = require('bluebird');
var multiparty = Promise.promisifyAll(require('multiparty'), {multiArgs:true})
var form = new multiparty.Form();
form.parse({}).then((data)=>{console.log(data)});
4

2 回答 2

8

这是我使用内置 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]);
    });
});

和用法:

const [fields, files] = await promisifyUpload(req)
于 2018-07-12T09:03:06.953 回答
0

我等到所有部分都被读取的解决方案:

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

这在您想要进一步处理零件的情况下非常方便,例如解析和验证它们,也许将它们存储在数据库中。

于 2019-07-04T21:57:12.033 回答