好吧,这是:
app.post('/upload', upload.single('songFile'), (req, res) => {
cloud_bucket.upload(req, res, console.log, res.send('1'));
});
有问题的功能是res.send(' 1');
这是cloud_bucket.upload:
module.exports = {
upload: function (req, res, next, fin) {
fileToBucket(req, res, next, fin);
}
}
//send file to cloud bucket
fileToBucket = (req, res, next, fin) => {
const file = req.file;
var url = '';
const gcsname = uuidv4() + file.originalname;
file2 = myBucket.file(gcsname);
const stream = file2.createWriteStream({metadata: {contentType: file.mimetype}});
stream.on('error', (err) => {
file.cloudStorageError = err;
next(err);
});
stream.on('finish', () => {
file.cloudStorageObject = gcsname;
file2.makePublic().then(() => {
file.cloudStoragePublicUrl = getPublicUrl(gcsname);
url = file.cloudStoragePublicUrl;
return url;
}).then((url) => {
console.log('upload complete');
metaToDb(req, url, res);
});
});
stream.end(file.buffer);
}
//send metadata to mysql
metaToDb = (req, url, res) => {
Song.create({
title: req.body.title,
description: req.body.description,
genres: req.body.genres,
owner: req.session.user.idUsers,
dateUploaded: new Date(),
URL: url
})
}
正如您所看到的,我并未在函数中的任何位置显式调用fin()。但是,除非我把它从初始函数调用中取出,否则会调用res.send(' 1')。
似乎在fileToBucket完成时自动调用(不是异步调用),但我想在其中一个承诺中调用它。