Node.js 在firebase云函数中,bucket.upload承诺过早解决
我写了一个这样工作的函数Node.js 在firebase云函数中,bucket.upload承诺过早解决,node.js,firebase,firebase-storage,es6-promise,google-cloud-functions,Node.js,Firebase,Firebase Storage,Es6 Promise,Google Cloud Functions,我写了一个这样工作的函数 onNewZipFileRequested {get all the necessary data} .then{download all the files} .then{create a zipfile with all those file} .then{upload that zipfile} (*here is the problem) .than{update the database with the signedUrl of the file} 这是
onNewZipFileRequested
{get all the necessary data}
.then{download all the files}
.then{create a zipfile with all those file}
.then{upload that zipfile} (*here is the problem)
.than{update the database with the signedUrl of the file}
这是相关代码
[***CREATION OF ZIP FILE WORKING****]
}).then(() =>{
zip.generateNodeStream({type:'nodebuffer',streamFiles:true})
.pipe(fs.createWriteStream(tempPath))
.on('finish', function () {
console.log("zip written.");
return bucket.upload(tempPath, { //**** problem****
destination: destinazionePath
});
});
}).then(()=>{
const config = {
action:'read',
expires:'03-09-2391'
}
return bucket.file(destinazionePath).getSignedUrl(config)
}).then(risultato=>{
const daSalvare ={
signedUrl: risultato[0],
status : 'fatto',
dataInserimento : zipball.dataInserimento
}
return event.data.ref.set(daSalvare)
})
在客户端,只要应用程序看到状态更改和新Url,就会出现一个下载按钮(指向新Url)
一切正常,但如果我尝试立即下载文件。。。还没有文件
如果我同时等待并重试,文件就在那里
我注意到我必须等待的时间取决于zipfile的大小
bucket.upload承诺应该在上传结束时解决,但显然触发得太早了。
有没有办法知道文件何时准备好?
我可能需要制作一个非常大的文件,如果这个过程需要几分钟,这不是问题,但是我需要知道它什么时候结束
*编辑*
代码中存在不必要的嵌套。虽然不是错误(重构前后的结果相同),但它在答案中造成了一些混乱,所以我将其编辑掉
我想指出的是,我只是在得到签名的url之后才更新数据库,而我是在上传之后才得到的(否则我就不能),所以要得到任何结果,承诺链必须工作,事实上它确实工作。当在客户端出现下载按钮时(当“状态”变为“fatto”时发生),它已链接到正确的签名url,但如果我过早按下该按钮,则文件不存在(失败-无文件)。如果我等待几秒钟(文件越大,我等待的时间就越长),那么文件就在那里
(英语不是我的母语,如果我不清楚,请提问,我会尽力更好地解释自己)看起来问题可能是大括号没有正确对齐,导致一个
语句嵌入另一个语句中。下面是将和语句分开的代码:
[***CREATION OF ZIP FILE WORKING****]}).then(() => {
zip.generateNodeStream({type: 'nodebuffer', streamFiles: true})
.pipe(fs.createWriteStream(tempPath))
.on('finish', function () {
console.log('zip written.')
return bucket.upload(tempPath, {
destination: destinazionePath
})
})
}).then(() => {
const config = {
action: 'read',
expires: '03-09-2391'
}
return bucket.file(destinazionePath).getSignedUrl(config)
}).then(risultato => {
const daSalvare = {
signedUrl: risultato[0],
status : 'fatto',
dataInserimento : zipball.dataInserimento
}
return event.data.ref.set(daSalvare)
})
我很困惑——看起来在一个then()块中有两个return语句。也许可以试着减少嵌套的数量——我认为你没有理由把一个then()放在另一个then()中。它们都可以按顺序相互跟随。谢谢,但不。我可以也应该避免这种嵌套(坏习惯),但这不会影响函数的结果。事实上,我刚刚尝试了你的代码,结果与预期完全一样:一切正常,但上传承诺解决得太早。这并不奇怪,因为您建议的重构发生在所讨论的承诺之后。。。