[英]How to fix “await is only valid in async function” even when await is in an async function in Node.js?
我有一些示例代码正在尝试运行,并且我希望同步执行一些正在执行的异步函数。 我知道您需要将异步添加到函数中以便进行等待。 我已经做到了。 虽然我得到以下错误:
let result = await promise;
^^^^^
SyntaxError: await is only valid in async function
at new Script (vm.js:80:7)
at createScript (vm.js:274:10)
at Object.runInThisContext (vm.js:326:10)
at Module._compile (internal/modules/cjs/loader.js:664:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
对于上下文,这是我的代码:
async function main() {
var client = Client.fromConnectionString(deviceConnectionString, Protocol);
fs.stat(filePath, function (err, fileStats) {
var fileStream = fs.createReadStream(filePath);
for (var i=0;i<10;i++) {
let promise = new Promise((res, rej) => {
client.uploadToBlob('testblob.txt', fileStream, fileStats.size, function (err, result) {
if (err) {
console.error('error uploading file: ' + err.constructor.name + ': ' + err.message);
} else {
console.log('Upload successful - ' + result);
}
res(i);
});
})
let result = await promise;
console.log(result);
}
fileStream.destroy();
});
}
main();
当我的函数已经异步时,为什么会出现错误提示?
您正在尝试在未标记异步(您的回调)的函数内使用异步等待。
只需将您的回调设为异步等待函数即可。
async function main() {
var client = Client.fromConnectionString(deviceConnectionString, Protocol);
fs.stat(filePath, async function (err, fileStats) {
var fileStream = fs.createReadStream(filePath);
for (var i=0;i<10;i++) {
let promise = new Promise((res, rej) => {
client.uploadToBlob('testblob.txt', fileStream, fileStats.size, function (err, result) {
if (err) {
console.error('error uploading file: ' + err.constructor.name + ': ' + err.message);
} else {
console.log('Upload successful - ' + result);
}
res(i);
});
})
let result = await promise;
console.log(result);
}
fileStream.destroy();
});
}
main();
let result = await promise;
上面的语句位于新的Promise回调处理程序中,该处理程序又是一个匿名函数。
因此,必须对此功能以及与新作用域相关联的异步操作,而这并不是一个新的promise对象。
let promise = new Promise(async (res, rej) => {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.