Resolving the SyntaxError: await is only valid in async function in Node.js

preview_player
Показать описание
---

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: For loop - SyntaxError: await is only valid in async function

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---

The Problem Explained

In your case, the error arises when trying to use the await keyword within a loop after invoking a promise. Here's a summary of what was happening in your original code:

[[See Video to Reveal this Text or Code Snippet]]

The use of await inside this then callback is what's causing the problem. Since then() is not an async function, trying to use await will throw the aforementioned error.

The Solution

To effectively utilize await, you need to ensure that it’s used inside an async function. Instead of combining then() with async/await, you should refactor your code to use await directly, without the promise chain. Here’s how:

Revised Code Structure

Here is the properly structured version of your code that eliminates the error:

[[See Video to Reveal this Text or Code Snippet]]

Step-by-Step Breakdown

Retrieve Products: First, you call getProducts and wait for it to resolve using await. This gives you the results directly.

Loop through Results: With results now available, you can directly loop over it using a for loop.

Await each Scrape: By calling await doScrape(results[i].productUrl); inside the loop, you ensure that each scrape completes before proceeding to the next URL. This maintains a clean, easy-to-read flow of asynchronous operations.

Conclusion

Рекомендации по теме
welcome to shbcf.ru