然后在promise resolve()完成之前调用Promise.all()

时间:2018-01-05 05:34:31

标签: node.js amazon-s3 restify formidable

我是节点新手。尝试构建一个服务,该服务将调用AWS以加载多个映像并将AWS密钥返回给客户端。在这里,我使用Promise all来完成所有AWS调用并获取AWS密钥,然后将一堆密钥返回给客户端。

但我很惊讶,Promise.all()then()在Promise resolve()之前被调用。急需帮助。请原谅我的坏节点代码。

server.post('/photo', function (req, res, next) {

    var form = new formidable.IncomingForm();
    var result = [];

    form.on('progress', function(bytesReceived, bytesExpected) {
        console.log('err');
    });

    form.on('error', function(err) {
        console.log('err',err);
    });

    form.on('end', function() {
        console.log('ended!!!!', arguments);
    });

    form.on('aborted', function() {
        console.log('aborted', arguments);
    });

    var urls = processAllFiles(form);
    Promise.all([urls]).then(function(result) {
        console.log('[][][]', urls);
    }).catch(function (err){
        console.log(err);
    });
    form.parse(req, function(err, fields, files) {
        console.log('am at parse');
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n', urls);
        res.end('received files:\n\n '+util.inspect(files));
    })
    return;

}) 

function processAllFiles(form) {
    var result = [];
    return new Promise(function (resolve, reject)
    {   try{
        form.onPart = function (part) {
            const params = {
                Bucket: 'xxxxx',
                Key: uuidv4() + part.filename
            };

            var upload = s3Stream.upload(params);

            upload.on('error', function (error) {
                console.log('errr', error);
            });
            upload.on('part', function (details) {
                console.log('part', details);
            });
            upload.on('uploaded', function (details) {
                result.push(details);
                console.log('uploaded', result);
            })
            part.pipe(upload);
        }
        resolve(result);
    } catch(exception){
        reject('error');
    }

    })
}

2 个答案:

答案 0 :(得分:1)

upload.on('uploaded', function (details) {
            result.push(details);
            console.log('uploaded', result);
            resolve(result);
        })

我认为你应该把决心放在异步函数的回调

答案 1 :(得分:0)

processAllFiles函数只返回1个promise,因此不需要Promise.all()。你可以直接做 processAllFiles.then(...) 请注意,Node.js是异步的,因此您调用的顺序可能无法按预期顺序解析(与同步调用相反)。