小编Jar*_*ton的帖子

JavaScript:Promise.All() 和 Async/Await 和 Map()

我试图理解为什么以下两个代码块会产生不同的结果。

第一个代码块按预期工作,并返回从数据库中查找的提供程序数组。另一方面,代码块二返回一个函数数组。我觉得我在理解 Promise.all() 和 async/await 时缺少一些简单的东西。

代码块的区别是:

  • 第 1 块:创建 promise 函数数组,然后使用 map 运算符将其包装在异步函数中。

  • 第 2 块:将 promise 函数数组创建为异步函数。因此,不会调用 map 运算符。

如果您不熟悉 Sequelize 库,被调用的 findOne() 方法会返回一个 promise。

另外值得一提的是,我知道我可以使用带有“name in” where 子句的单个查找查询来获得相同的结果,而无需为多个选择查询创建一组 promise。我这样做只是作为 async/await 和 Promise.all() 的学习练习。

代码块 1:在 Promise.all() 中使用 map()

private async createProfilePromises(profiles){

    let profileProviderFindPromises = [];

    //Build the Profile Providers Promises Array.
    profiles.forEach(profile => {
        profileProviderFindPromises.push(
            () => {
                return BaseRoute.db.models.ProfileProvider.findOne({
                    where: {
                        name: {[BaseRoute.Op.eq]: profile.profileProvider}
                    }
                })}
        );
    });

    //Map and Execute the Promises
    let providers = …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous promise async-await sequelize.js

4
推荐指数
1
解决办法
6524
查看次数