The word "await" is a special reserved keyword used to call functions within an async

Currently utilizing async-await: Whenever the function run invokes findLateastVersion, even though run function is marked as async, an error message pops up stating await is a reserved word. The findLateastVersion method returns a promise and based on various tutorials, everything should be in working order. So, why does this pesky error persist?

async function findLateastVersion(surveyName, db) {

return new Promise((resolve, reject) => {
    try {
        const refv = await db.collection('surveys').doc(surveyName).collection('versions').orderBy('timestamp'); //reference to specific version docs
        console.log(refv);
        let docName = refv.firebase.firestore.FieldPath.documentId();

        resolve(docName);
        // const versions = refv.where(firebase.firestore.FieldPath.documentId(), '!=').orderBy("timestamp").limit(1); 
    } catch (err) {
        console.log('err: ', err);
    }
    reject("error")
});

}

async function run() {
const db = await connectToFirestore();
const surveyName = argv.s || argv.surveyName;
const surveyVersion = argv.v || argv.surveyVersion;

const names = ['a', 'b', 'c'];
if (!surveyName) {
    names.forEach(async function (surveyname) {
        console.log("surveyname", surveyname)
        const version = await findLateastVersion(surveyname, db)
        //getSurveyData(surveyname, version, db);

    });
}

//await getSurveyData(surveyName, surveyVersion, db);
}

Answer №1

If you want to use await, it must be inside functions marked as async. Here is a solution for your issue:

names.forEach(function (surveyname) {
    console.log("surveyname", surveyname)
    const version = await findLateastVersion(surveyname, db)
    //getSurveyData(surveyname, version, db);

});

To resolve this problem, you can simply add async to the callback function like so:

names.forEach(async function (surveyname) {
    console.log("surveyname", surveyname)
    const version = await findLateastVersion(surveyname, db)
    //getSurveyData(surveyname, version, db);
});

Alternatively, you can use an asyncForEach implementation as shown below:

async function asyncForEach(array: any[], callback: (value: any, index: number, array: any[]) => void) {
    for (let index = 0; index < array.length; index++) {
        await callback(array[index], index, array);
    }
}

await asyncForEach(names, async function (surveyname) {
    console.log("surveyname", surveyname)
    const version = await findLateastVersion(surveyname, db)
    //getSurveyData(surveyname, version, db);
});

The second option allows you to await all the callbacks to be completed before moving on.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to resolving an issue with importing a css file in next.js?

Error: ./node_modules/quill-emoji/dist/quill-emoji.css ModuleParseError: Module parse failed: Unexpected character '�' (1:0) You may need a suitable loader for handling this file type, as there are currently no configured loaders to process it. ...

Utilizing React Typescript Discriminating Unions to choose between two different types based solely on props

In my project, I have a component that consists of different types: type Base = { color: string } type Button = { to: string } & Base type Link = { link: string linkNewTab: boolean } & Base type ComponentProps = Button | Link e ...

Retrieve container for storing documents in JavaServer Pages

Previously, I created JSP and HTML code to upload a file from the hard disk into a database using <input type="file" name="upfile"> However, a dialog box with an "Open" button is displayed. What I am looking for is a "Save" button that will allow u ...

Creating an attractive image carousel using jQuery or YUI for your website

I am searching for a javascript-based slideshow solution for images. I have received the following requirements: The slideshow should fade one image into another, looping back to the first image after all images have been displayed It must include naviga ...

Having trouble uploading Node.js and Mongoose to Heroku due to error codes H12 and H15? Need help troubleshooting and resolving this issue?

Attempting to deploy my Node, mongoose, express app on Heroku for the first time has been a challenge. The application is a simple blog with a login system. Despite extensive research and effort, I am struggling to successfully host it. Below is the error ...

Protractor and Jasmine fail to fulfill the promise of retrieving a webpage title

I am facing an issue with my protractor/jasmine test code where it only prints out 1 and 2, then hangs and times out. It seems like there might be a problem with the click() action on the button element or the promise on the getTitle method of the browser ...

What sets apart initializing an Express app using "app = new Express()" compared to "app = express()"?

Throughout my experience, express apps have always been initialized like this: var express = require('express') var app = express() However, today I came across an example where a new operator was used: var Express = require('express&apos ...

Is Webpack bundling the node_modules of node_modules into the bundle?

Recently, I noticed that webpack is bundling dependencies from the top-level node_modules directory into my actual bundle. For instance, one of my dependencies, example-dep, relies on lodash and has a nested node_modules directory at node_modules/example-d ...

Why is the responseText from XMLHttpRequest always stripped of tags in AJAX?

Whenever the server sends the XML string to the client using the XMLHttpRequest object, I noticed that when I insert the text inside the div tags, it appears without any tags. However, I actually need the XML tags to be present so that I can parse the cont ...

I need help using i18N to translate the SELECT option in my VUE3 project. Can someone guide me

<n-select v-model:value="value" :options="options" /> options: [ { label: "Every Person", value: 'file', }, { label: 'Drive My Vehicle', ...

AJAX Form Submission for CommentingAJAX allows for seamless form submission

Currently facing an issue with a form submission that is not displaying comments without refreshing the page. When the submit button is clicked, it redirects to the top of the page without executing any actions - no insertion into the database and subseque ...

Looking for a way to dynamically append a child element within another child

Struggling to include a new child within a specific child in Json myObject:any[] = []; this.myObject = { "type": "object", "properties": { "first_name": { "type": "string" }, "last_name": { "type": "string" }, } } addF ...

Setting minimum or maximum dates in jquery-simple-datetimepicker is proving to be challenging

Currently, I am utilizing the following library: In this jsfiddle example: http://jsfiddle.net/3SNEq/2/, everything works perfectly when setting minDate or MaxDate directly in the appendDtpicker method. However, when trying to use handleDtpicker like thi ...

What is the best way to right-align a label in a vertical MUI Slider in ReactJS?

I am currently working with ReactJS/TS and MUI (Material-UI) to develop a vertical slider that requires the label to be positioned on the right side. By default, MUI places the label on the left for vertical sliders. I have reviewed the API documentation e ...

Ensure data accuracy by triggering the cache - implementing SWR hook in Next.js with TypeScript

I recently implemented the swr hook in my next.js app to take advantage of its caching and real-time updates, which has been incredibly beneficial for my project (a Facebook clone). However, I encountered a challenge. The issue arises when fetching public ...

Navigate to a fresh HTML page upon form submission

I'm completely new to the world of web apps and JavaScript, and I'm facing an issue where my form submission doesn't redirect me to a thank you page. Instead, it just leads to a blank page every time. I've tried researching solutions on ...

Altering the hue of various stroke patterns

I've encountered an issue where I want to create skill bars that display my skills in percentages. Luckily, I found a great code that allows me to do this. Although I would prefer to do it myself, I haven't come across a good tutorial that teache ...

Custom pagination with onSelectionModelChange in React Material UI Data Grid

Has anyone encountered a problem with using the DataGrid component's onSelectionModelChange prop? I can successfully retrieve the selected rows for a single page, but when I implement custom pagination and navigate to the next page, the previous selec ...

Searching for nested divs with the same class name in jQuery can be achieved by using the

Need assistance in locating all divs with a specific class name. Some divs may have nested divs with the parent div's class name. Take this scenario for example: <div class="myForm"> <div class ="myDiv"> <div class ="myDiv"> ...

A guide to resizing images in Node.js prior to using the writeFile function

var file_path = files.file.path; fs.readFile(file_path, function (err, data) { fs.writeFile(file_path, data, function (err) { res.end(JSON.stringify({ message: 'file uploaded successfully', success: true }); }); }); I exp ...