I have some sample code I'm trying to run, and I want some asynchronous function that is executing to be called synchronously. I know you need to add async to the function in order to have an await. I've already done that. Still though I get the following error:
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)
For context here is my code:
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();
Why am I getting said error when my function is already async?
fs.stat(filePath, function (err, fileStats) {this function also needs to be async.fs.stat(filePath, function (err, fileStats) {– everything is inside this callback function, which is not an async function… even if you unindent the code so it looks like it’s not in that function. Uselet fileStats = await fs.promises.stat(filePath).