Parsing error unexpected reserved word await

Learn how to easily fix the "unexpected reserve word" error for the "await" keyword in JavaScript.

The “unexpected reserved word (await)” error occurs in JavaScript when you use the await keyword in a function that is not specified as async. To fix it, add an async modifier to the function to mark it as async.

The "Unexpected reserved word 'await'" error occurring in JavaScript.

The “Unexpected reserved word ‘await’” error occurring in JavaScript.

Here’s an example of the error occurring:

function getName() { // ❌ SyntaxError: Unexpected reserved word const str = await Promise.resolve('Coding Beauty'); return str; }

Note: As this is a syntax error, the function doesn’t need to be invoked for it to be detected, and no part of the code runs until it is resolved.

The async and await keywords work together in JavaScript (hence the commonly used term, async/await); to use the await keyword in a function, you must add the async modifier to the function to specify that it is an async function.

// ✅ Use "async" keyword modifier async function getName() { // ✅ Successful assignment - no error const str = await Promise.resolve('Coding Beauty'); return str; }

Fix “Unexpected reserved word (await)” error in nested function

If you’re using the await keyword, it’s likely that you already know that it has to be in an async function. What probably happened is that you nested functions and mistakenly ommited the async modifier from the innermost function containing the await keyword.

For example:

// ❌ SyntaxError: Unexpected reserved word export const createTask = async ({ description }) => // ❌ "async" keyword missing from innermost function (dispatch) => { await fetch('https://example.com/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ description }), }); dispatch({ type: 'taskCreated', description }); };

For await to work, the deepest function in the nesting hierarchy is required to be specified as async. It won’t work even if any or all of the outer functions are marked as async.

So we resolve the error in this case by adding the async modifier to the innermost function:

// ✅ No error export const createTask = async ({ description }) => // ✅ Innermost function marked as async async (dispatch) => { await fetch('https://example.com/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ description }), }); dispatch({ type: 'taskCreated', description }); };

In this example, we should be able to remove the async keyword from the outer function, as it isn’t performing any asynchronous operations with await, but this depends on whether the caller of createTask() is expecting it to return a Promise or not.

Here’s another example where this mistake frequently happens; using await in an array looping method:

// ❌ SyntaxError: Unexpected reserved word async function processPhotos(photoIds) { const data = await Promise.all(photoIds.map((photoId) => { const res = await fetch(`http://example.com/photos/${photoId}`); return await res.json(); })); // process data... }

Like in the previous example, the error occurs because the async keyword modifier is absent from the map() callback, even though it’s present in the function that calls map(). The fix is the same, add async to the map() callback.

// ✅ No error async function processPhotos(photoIds) { const data = await Promise.all( photoIds.map(async (photoId) => { const res = await fetch(`http://example.com/photos/${photoId}`); return await res.json(); }) ); // processing... }

Use await at top level

If you’re trying to use await at the top level of your file, you’ll need to set the type attribute to "module" in the script tag referencing the file in the HTML. This works when your code runs in browser environments.

For example:

<script type="module" src="index.js"></script>

Now you’ll be able to use await at the global scope in your file, e.g.:

console.log(await Promise.resolve('Coding Beauty'));

If you’re using Node.js, you’ll need to set the type attribute to "module" in your package.json file.

{ "name": "cb-js", "type": "module", "version": "1.0.0", "main": "index.js", "license": "MIT", // other fields... }

If there’s no package.json in your project directory, you can create one with the following command

# NPM npm init -y # Yarn yarn init -y

The await keyword will now work at the top level of your project files.

Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

I am trying to use await with my API call but I am facing the following error: Unexpected reserved word ‘await’ in ReactJS. In this Exerror article, We are going to learn about How to reproduce this error and we will discuss All Possible Solutions Let’s Get Start with This Article.

Contents

  1. How Unexpected reserved word ‘await’ Error Occurs?
  2. How To Solve Unexpected reserved word ‘await’ Error?
  3. Solution 1: declare Async
  4. Conclusion

How Unexpected reserved word ‘await’ Error Occurs?

I am trying to use await with my API call but I am facing the following error.

Unexpected reserved word 'await'

So here I am writing all the possible solutions that I have tried to resolve this error.

How To Solve Unexpected reserved word ‘await’ Error?

  1. How To Solve Unexpected reserved word ‘await’ Error?

    To Solve Unexpected reserved word ‘await’ Error If you are not declaring your function to async then you are not able to Use await. To solve the Unexpected reserved word ‘await’ You need to declare your function as a async function and then you can use await. Now, You can use await without facing an error, and now your error must be resolved. Thank You.

  2. Unexpected reserved word ‘await’

    To Solve Unexpected reserved word ‘await’ Error If you are not declaring your function to async then you are not able to Use await. To solve the Unexpected reserved word ‘await’ You need to declare your function as a async function and then you can use await. Now, You can use await without facing an error, and now your error must be resolved. Thank You.

Solution 1: declare Async

If you are not declaring your function to async then you are not able to Use await. To solve the Unexpected reserved word ‘await’ You need to declare your function as a async function and then you can use await. Here is my example.

async function myApiCall() {  // Declare async Here
  const myData = await axios.get('my_api_call);   // Now you can use Await
  return myData;
}

Now, You can use await without facing an error, and now your error must be resolved. Thank You.

Conclusion

It’s all About this error. I hope We Have solved Your error. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Also, Read

  • How to use a switch Case statement inside a React component?
  • type is invalid — expected a string (for built-in components) or a class/function
  • Component definition is missing displayName (react/display-name)
  • Maximum update depth exceeded. This can happen when a component repeatedly calls
  • Export namespace should be first transformed by @babel/plugin-proposal-export-namespace-from

Содержание

  1. Parsing error unexpected reserved word await
  2. Unexpected reserved word ‘await’ error in JavaScript #
  3. Conclusion #
  4. error with await «Parsing error: Unexpected token» #319
  5. Comments

Parsing error unexpected reserved word await

Reading time В· 2 min

Unexpected reserved word ‘await’ error in JavaScript #

The «unexpected reserved word await» error occurs when the await keyword is used inside of a function that was not marked as async . To use the await keyword inside of a function, mark the directly enclosing function as async .

Here are 2 examples of how the error occurs.

We didn’t declare the getString function as async , so we aren’t able to use the await keyword in it. Instead, we should mark the function as async .

Keep in mind that the directly enclosing function has to be marked as async for you to be able to use the await keyword.

We marked the loopThrough function as async , however, we’re using the await keyword inside of the function we passed to the forEach method.

Instead, we should have marked the function we passed to forEach as async .

We declared the function we passed to the forEach method as async, therefore we are able to use the await keyword in it.

If you’re trying to use the await keyword at the top level, make sure you set the type attribute to module in your package.json file if you’re using node.js or set the attribute in a script tag in the browser.

If you’re in a browser environment, set the type attribute to module in your script tag to be able to use top level await .

Now you can use top level await in your code, e.g.

And here’s how to use top level await in Node.js.

Create package.json file if you don’t have one already:

Add the type property and set it to module in your package.json file.

Now you can use top-level await in your Node.js code.

Conclusion #

The «unexpected reserved word await» error occurs when the await keyword is used inside of a function that was not marked as async . To use the await keyword inside of a function, mark the directly enclosing function as async .

Источник

error with await «Parsing error: Unexpected token» #319

I am using a async/await library (https://github.com/yortus/asyncawait) to call Promises as if they are running synchronously. here is example:
it(‘Should update user info’, async(function() <
let configInfo = await(userConfig.getConfig())
.
await(funds.waitForPaymentsMethodsScreen())
await(funds.navigateToAddCreditDebitCardSync())
.
>))
This code execute fine, but doesn’t pass the eslint test. Running grunt eslint, I get following error.
«Parsing error: Unexpected token», for the parenthesis after await.

Is there way to resolve this error?

The text was updated successfully, but these errors were encountered:

And you are using babel-eslint? if its configured properly it should work fine. There isn’t enough information here without your config, and version

Is this the information you are looking for, I am wondering what rule/configuration I need to avoid this error.

babel-eslint => «version»: «6.0.4»,

«rules»: <
«arrow-body-style»: 0,
«block-spacing»: [2, «always»],
«comma-dangle»: [2, «never»],
«constructor-super»: 2,
«eqeqeq»: [2, «smart»],
«func-names»: 0,
«key-spacing»: [2, < beforeColon: false, afterColon: true, mode: «minimum» >],
«max-len»: [2, 120, 4, < ignoreComments: true >],
«no-array-constructor»: 2,
«no-catch-shadow»: 2,
«no-class-assign»: 2,
«no-dupe-class-members»: 2,
«no-empty-pattern»: 2,
«no-extra-boolean-cast»: 2,
«no-multi-spaces»: 0,
«no-multiple-empty-lines»: [2, < max: 1, maxEOF: 1 >],
«no-nested-ternary»: 0,
«no-param-reassign»: [2, < props: false >],
«no-self-compare»: 0,
«no-this-before-super»: 2,
«no-unexpected-multiline»: 2,
«no-unused-expressions»: 0,
«no-unused-vars»: [2, < vars: «local», args: «none» >],
«no-useless-call»: 2,
«no-void»: 2,
«object-shorthand»: [2, «methods»],
«prefer-arrow-callback»: 0,
«prefer-template»: 0,
«space-unary-ops»: 2,
«wrap-iife»: [2, «inside»]
>

The rules aren’t necessary — I mean the other parts like parser: «babel-eslint»

you mean grunt config
module.exports = function(grunt) <
grunt.initConfig( <
pkg: grunt.file.readJSON(‘package.json’),
eslint: <
options: <
parser: ‘babel-eslint’
>,
target: [‘test/.js’, ‘lib/__/.js’]
>
>);
require(‘load-grunt-tasks’)(grunt);
>;

I’ve got a similar problem. My code looks like this:

I receive following error

Removing the parens doesn’t help:

Parsing error: Unexpected token dispatch

Источник

;
Date: Sun Aug 07 2022

Tags:
Node.JS »»»» JavaScript

The error Unexpected Reserved Word usually means you’re using await in a non-async function. But what if Mocha throws this error, citing a test suite file that’s clean of such problems? To save spending fruitless hours, read this short article.

The error Unexpected Reserved Word means that the JavaScript compiler saw a reserved word, meaning a keyword special to the compiler, when it wasn’t expected. THe typical case is using await in a function that hasn’t been marked async.

In this case I found Mocha — a popular framework for writing unit tests — to incorrectly report which source file contained the unexpected reserved word. My test suite threw that error message, but Mocha identified the incorrect source file.

Usually a compiler, or a test framework, reporting a syntax error will tell us the actual line of code, and the offending code. But, in this case Mocha does not report the line number, nor the affected code, and to make it worse it reports the error as occuring in a different source file from its actual location.

Because Mocha incorrectly reported the location of the unexpected reserved word error, I spent fruitless hours double and triple checking the syntax of a source file which contained no such error.

Let’s start with the usual case:

$ cat unreserved.mjs 

function a() {
    await console.log(`This will throw an error`);
}

$ node unreserved.mjs 
file:///home/david/Projects/akasharender/akasharender/test/unreserved.mjs:3
    await console.log(`This will throw an error`);
    ^^^^^

SyntaxError: Unexpected reserved word
    at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:119:18)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:483:14)
    at async link (node:internal/modules/esm/module_job:67:21)

This is what we normally see. We’ve created an ES6 module, unreserved.mjs, containing a non-async function. Within that function is the await keyword. That’s a use of a reserved word, await, in the incorrect context. In this case the error report does an excellent job of letting us know what the problem is, and where it occurred.

This is the desired behavior, for the compiler to do a good job of letting us know what’s going on. We can go directly to the affected line of source code, and immediately know what to do, after groaning «Doh«.

Consider a real package, where an actual (and useful) module has been written, which contains that problem. Then, you go to write a test suite for this module, because you’re following good test-first-development practices.

$ cat test-unreserved.mjs 

import * as unreserved from './unreserved.mjs';

$ npx mocha test-unreserved.mjs 

SyntaxError[ @/home/david/Projects/akasharender/akasharender/test/test-unreserved.mjs ]: Unexpected reserved word
    at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:119:18)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:483:14)

Your test suite of course must import the application code to execute test cases. This means the unreserved.mjs module. Because we just created that file, we can easily remember the error. In this case, Mocha doesn’t give us a clean error message. It simply says Unexpected reserved word, and further it identifies test-unreserved.mjs as containing the problem.

Again, consider that this is instead happening in a real package. The test suite could have 1500 lines of code, and the module being tested has a similar amount of code.

Because Mocha positively identifies the test suite as containing the unexpected reserved word, it’s easy to then spend several hours combing through the test suite. You check every use of await and it’s all correct. You check closely every loop, every function, every test case. You use VS Code and collapse every block, and because the editor correctly collapses each block, it seems the editor believes this is correctly constructed JavaScript. You then try commenting out all code, and still the error shows up. Finally you try commenting out the import statements one by one, and voila the error goes away with one particular import statement.

Checking inside that file you might then find a non-async function where the async keyword was used. That’s easily fixed, and that particular error goes away. There may have been other problems, and you’ll know the original problem was fixed because the error message changes.

$ npx mocha test-cache.mjs 

SyntaxError[ @/home/david/Projects/akasharender/akasharender/test/test-cache.mjs ]: Unexpected reserved word
    at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:119:18)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:483:14)

$ npx mocha test-cache.mjs 

SyntaxError[ @/home/david/Projects/akasharender/akasharender/test/test-cache.mjs ]: Identifier 'setup' has already been declared
    at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:119:18)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:483:14)

This is from the real instance where the problem occurred. I had fixed the unexpected reserved word issue, only to learn of another problem — that I’d created two functions named setup. Notice that Mocha still reported the wrong source file. But, its clear the problem will be in the other source file and not the test suite.

Conclusion

Mocha is incorrectly reporting the source file containing the code problems.

It correctly identified the problem — that some code used a reserved word incorrectly. But the error was reported in the wrong file, which can easily lead to fruitless hours carefully scrutinizing code that has no such errors.

Our time is valuable, and it’s frustrating to spend so much time cleaning up a file that had no problems in it.

Bad Mocha. No soup for you.

About the Author(s)


(davidherron.com)
David Herron
:
David Herron is a writer and software engineer focusing on the wise use of technology. He is especially interested in clean energy technologies like solar power, wind power, and electric cars. David worked for nearly 30 years in Silicon Valley on software ranging from electronic mail systems, to video streaming, to the Java programming language, and has published several books on Node.js programming and electric vehicles.

Books by David Herron

(Sponsored)

Понравилась статья? Поделить с друзьями:
  • Parsing error the type cast expression is expected to be wrapped with parenthesis
  • Parent contains error record exception
  • Pantum m7100dn ошибка принтера 05
  • Pantum bm5100adn ошибка принтера 02
  • Panotour pro fatal error xml loading failed