使用Google Storage API时如何等待javascript回调执行完成再走后续逻辑
问题原因
file.save方法支持回调、Promise两种调用模式:当你传入回调参数时,方法不会返回Promise对象,此时await不会生效,代码会直接执行后续的console.log,因此会出现LastMessage比成功/错误日志先打印的问题。
解决方法
方案1:使用async/await + try/catch(推荐)
移除回调参数,直接等待file.save返回的Promise,用try/catch捕获异常:
try { await file.save(jsonData.trim(), { resumable: false }) console.log('success') } catch (error) { console.log('error') } console.log("LastMessage: Error or Success is received, only then log this message")
方案2:手动封装回调为Promise
如果需要保留回调逻辑,可手动将方法封装为Promise后再等待:
const saveResult = new Promise((resolve, reject) => { file.save(jsonData.trim(), { resumable: false }, function(error) { if (error) { console.log('error') reject(error) } else { console.log('success') resolve() } }) }) await saveResult console.log("LastMessage: Error or Success is received, only then log this message")
内容的提问来源于stack exchange,提问作者Ritush
相关产品推荐
相关产品推荐

