【问题标题】:How to order awaits in asynchronous method如何在异步方法中订购等待
【发布时间】:2020-12-06 18:15:12
【问题描述】:
async getRecords(): Promise<Records[]> {
    this.subRecords = await this.afs.collection<Records>('records')
        .valueChanges()
        .subscribe((data: Records[]) => {
            console.log('log before data saved');
            this.records = data as Records[];
        });
    console.log('log before return');
    return await this.records;
}

所以我的问题是,我需要以正确的顺序执行此代码。 log before data saved 在返回后执行。所以我并没有真正及时保存我的数据。我需要一种方法来命令代码的执行,以便函数返回我的 this.records 数组中的记录。

【问题讨论】:

    标签: angular typescript firebase asynchronous google-cloud-firestore


    【解决方案1】:

    如果您想从单个查询返回数据,则不应使用valueChanges(),因为它不会返回承诺。 valueChanges 用于为可能随时间变化的数据设置侦听器。

    对于您的情况,请改用 get(),它会返回一个使用查询结果解析的承诺,如 here 所示。

    await this.afs.collection<Records>('records').ref.get()
    

    【讨论】:

    • 感谢您的通知,但基本上问题仍然存在,因为无论我如何更改获取数据的方法,问题都是按照代码处理的顺序。
    猜你喜欢
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    相关资源
    最近更新 更多