24
loading...
This website collects cookies to deliver better user experience
node ./my-script.js
and then boom!, you get something like this?SyntaxError: await is only valid in async function
at wrapSafe (internal/modules/cjs/loader.js:1070:16)
at Module._compile (internal/modules/cjs/loader.js:1120:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
async function doSomethingAsync() {
return Promise.resolve('Hello, World!');
}
const response = await doSomethingAsync();
console.log(response);
async function doSomethingAsync() {
return Promise.resolve('Hello, World!');
}
(async function() {
const response = await doSomethingAsync();
console.log(response);
})();
node ./my-script.js
now produces Hello, World! as expected.async function printAsync(text) {
return Promise.resolve(text);
}
(async function(text) {
const response = await printAsync(text);
console.log(response);
})('Hello, World!');
printAsync
and our IIFE now accept a text
argument, which we provide when we invoke the IIFE.async/await
brings to the table. Catch ya!