Skip to content
Advertisement

SyntaxError when using try/catch with aync/await in NodeJS [closed]

I am a beginner in Node Js. I am not able to figure out why the below code gives syntax error with catch().I have upgraded the Node JS V14. Any help will be appreciated here

async function demoPromise() {
    try {
        let message1 = await myFirstPromise;
        let message2 = await helloPromise();
        console.log(message2);
    } catch ((error) => {
        console.log("Error:" + error.message);
    })
}

(async () => {
    await demoPromise();
})();

Error:

nodejsmarkasyncAwait.js:7
    } catch ((error) => {
             ^

SyntaxError: Unexpected token '('
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

Advertisement

Answer

catch doesn’t expect a function, it’s just a special syntax to detect the error:

try {
  
} catch(error) {

}
Advertisement