[英]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.