0

我寫了這樣的工作在火力雲功能的bucket.upload承諾解決太早

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後才更新數據庫,並且只有在上傳之後才能獲得該數據庫(否​​則我不能這樣做),因此要在所有promise鏈中獲得任何結果必須正常工作,事實上它的確如此。當客戶端出現下載按鈕時(發生'狀態'變成'fatto'時),它已經鏈接到正確的簽名url,但如果我按它太早,文件不存在(失敗 - 沒有文件)。如果我等一會兒(文件越大,我必須等待的時間越長),那麼文件就在那裏。

(英語不是我的母語,如果我一直不清楚問,我會嘗試更好地解釋自己)

+0

我很困惑 - 它看起來像你有一個那麼()塊內的兩個return語句。也許嘗試減少嵌套的數量 - 我認爲你沒有理由把then()放在另一個then()中。他們都可以依次相繼。 –

回答

1

它看起來像這個問題可能是括號沒有正確對齊,導致then聲明嵌入到另一箇中。下面是分離then語句代碼:

[***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) 
}) 
+0

謝謝,但沒有。我可以也許應該避免這種嵌套(壞習慣),但是這不會影響函數的結果。事實上,我只是嘗試了你的代碼,結果與預期完全一樣:一切正常,但上傳承諾過早解決。這並不令人驚訝,因爲您提出的重構是在承諾問題之後發生的...... –