宣传多党派

时间:2018-05-25 05:53:38

标签: node.js promise bluebird multiparty

我正在宣传多方使用其form.parse。它运行正常但是form.parse没有返回我可以使用then / catch值的promise。

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 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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));

如果您想进一步处理部件,例如解析和验证它们,或者将它们存储在数据库中,这可能会很方便。