简体   繁体   English

typescript 中的异步等待未按预期工作

[英]Async await in typescript not working as expected

I wrote a method in typescript which is supposed to return collection list name of mongo db.我在 typescript 中写了一个方法,它应该返回 mongo db 的集合列表名称。

public async getTables(): Promise<String[]> {
    let collectionNames = [];
    const connection = await mongoose.connect("mongodb://localhost/test");
    await mongoose.connection.on('open', async function () {
        mongoose.connection.db.listCollections().toArray(function (err, tables) {
            console.log(tables);
            tables.forEach(element => {
                collectionNames.push(element["name"]);
            });
            console.log(collectionNames);

            mongoose.connection.close();
        });
    });

    return collectionNames;

}

Problem is instead of awaiting it returns directly empty collection list name.What is the issue here.问题不是等待它直接返回空的集合列表名称。这里的问题是什么。

Because you use "await" in here,因为你在这里使用“等待”,

const connection = await mongoose.connect("mongodb://localhost/test");

So, you miss "open" event that mongoose connection emit.因此,您错过了 mongoose 连接发出的“打开”事件。

You can remove "await" for your program run as you expected您可以按预期删除程序运行的“等待”

public async getTables(): Promise<String[]> {
   let collectionNames = [];
   const connection = mongoose.connect("mongodb://localhost/test");
   await mongoose.connection.on('open', async function () {
        mongoose.connection.db.listCollections().toArray(function (err, tables) {
           console.log(tables);
           tables.forEach(element => {
               collectionNames.push(element["name"]);
           });
           console.log(collectionNames);

           mongoose.connection.close();
       });
});

return collectionNames;
}

Or you can write as below或者你可以像下面这样写

public getTables(): Promise<String[]> {
return new Promise(async (resolve, reject) => {
    try {
        let collectionNames = [];
        const connection = await mongoose.connect("mongodb://localhost/test");
        mongoose.connection.db.listCollections().toArray(function (err, tables) {
            console.log(tables);
            tables.forEach(element => {
                collectionNames.push(element["name"]);
            });
            console.log(collectionNames);

            mongoose.connection.close();
            resolve(collectionNames);
        });
    } catch (e) {
        reject(e);
    }
    
})
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM