0

I'm using async-await: the function run calls to findLateastVersion, run function is async but I'm keep getting the error await is a reserved word, findLateastVersion returns promise and according to diffrent tutorials it should work.. why is this error still happening?

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(function (surveyname) {
        console.log("surveyname", surveyname)
        const version = await findLateastVersion(surveyname, db)
        //getSurveyData(surveyname, version, db);

    });
}

//await getSurveyData(surveyName, surveyVersion, db);
}
j.her
  • 187
  • 1
  • 2
  • 11
  • 2
    just remove the `new Promise` wrapper - it's not needed with `async` – georg Jun 16 '19 at 10:01
  • 1
    Instead of `forEach`, use a `for ... of` construct so that you don't need a callback function for it. Then the `await` will truly occur within your `async` function. – trincot Jun 16 '19 at 10:08

1 Answers1

0

You can use await only inside functions marked as async. Here is your problem:

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

});

You should either simply add async to callback function

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

or use some asyncForEach implementation, similar to the next one:

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);
});

Second variant allows you to await all the callbacks to be finished

Sergey Mell
  • 7,780
  • 1
  • 26
  • 50