await是保留字-来自异步函数的调用

时间:2019-06-16 09:57:59

标签: javascript async-await

我正在使用async-await: 该函数对findLateastVersion的运行调用,运行函数是异步的,但我不断收到错误await is a reserved wordfindLateastVersion返回promise,并且根据不同的教程,它应该可以工作。 为什么仍会发生此错误?

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

1 个答案:

答案 0 :(得分:0)

您只能在标记为await的函数中使用async。这是您的问题:

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

});

您应该只是将异步添加到回调函数中

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

或使用一些asyncForEach实现,类似于下一个实现:

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

第二个变体允许您等待所有回调完成