[英]Wait for javascript callback function to finish
我正在使用 google storage api 在異步函數中將文件保存在 gcp 存儲桶中。 我想等到回調中出現錯誤或成功,然后才想繼續執行其他代碼行,但我在成功或錯誤之前收到 LastMessage。
https://googleapis.dev/nodejs/storage/latest/File.html#save
await file.save(jsonData.trim(), {resumable : false}, function(error) {
if (error) {
console.log('error');
} else {
console.log('success');
}
})
console.log( "LastMessage: Error or Success is received, only then log this message")
您的.save()
沒有返回承諾。 而是給出回調。 您可以創建一個傳統的 promise 方法來實現您想要實現的目標。 這是代碼片段 -
const saveFile = (jsonData) => {
return new Promise((resolve, reject) => {
file.save(jsonData.trim(), { resumable: false }, function (error) {
if (error) {
console.log('error');
reject()
} else {
console.log('sucess');
resolve()
}
})
})
}
await saveFile()
console.log("LastMessage: Error or Success is received, only then log this message")
文檔中有一個例子
https://googleapis.dev/nodejs/storage/latest/File.html#save-examples
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');
const file = myBucket.file('my-file');
const contents = 'This is the contents of the file.';
file.save(contents, function(err) {
if (!err) {
// File written successfully.
}
});
//-
// If the callback is omitted, we'll return a Promise.
//-
file.save(contents).then(function() {});
您不需要使用等待,對於您的示例,您可以嘗試以下操作:
file.save(jsonData.trim(), {resumable : false})
.then(() => nextFunc())
.catch(() => nextFunc())
function nextFunc() {
console.log( "LastMessage: Error or Success is received, only then log this message")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.