javascript - 在 promise 内部,我想将值(该值本身来自另一个 promise )分配给将在该 promise 之外使用的变量

标签 javascript firebase promise async-await

在我的 Firestore DB 中,我有两个集合 bookscategories。在categories集合中,所有文档只有一个字段,即name,而在books集合中,文档包含多个字段,其中之一是type,即数据类型 DocumentRef 的数组,这意味着书籍中的每个文档可以有多个类别名称值。

现在,对于 books 集合中的每个文档,我想在单个字符串中获取关联类别名称的所有值。

这就是我到目前为止所拥有的。

database
    .collection("books")
    .get()
    .then(snapshot => {
        snapshot.forEach(doc => {
            renderTypes(doc);
        });
    });

/** The renderTypes function **/
renderTypes = doc => {
    let typeArrayRef = doc.data().type; // assigning the array of documentRefs

    console.log("total elements in types array is ", typeArrayRef.length);
    promiseVar = new Promise((resolve, reject) => {
        typeList = " ";
        // looping through each items inside the array
        typeArrayRef.forEach(type => {
            type.get().then(res => {
                typeList = typeList + " " + res.data().name;
            });
            // unccommenting this line gives a mixed output (out of order)
            // console.log(`String containing all the types are ${ type }`);
        });
        resolve(type); // resolving with type string
    });

    promiseVar.then(type => {
        console.log("Inside the then of promiseVar", type);
    });
};

现在我得到的输出是:

total elements in types array is 6 
total elements in types array is 3
total elements in types array is 1 

Inside the then of promiseVar
Inside the then of promiseVar 
Inside the then of promiseVar

最后三行没有打印任何内容,但将其记录在 promiseVar 中会给出输出,但是是混合的(即没有固定顺序)。

看起来promiseVar正在立即解决。有什么办法可以解决这个问题吗?

最佳答案

如果要聚合异步值列表,可以使用 Promise.all然后计算结果。在您的情况下,它可能看起来像这样:

renderTypes = doc => {
    const typeArrayRef = doc.data().type; // assigning the array of documentRefs
    console.log("total elements in types array is ", typeArrayRef.length);

    const promiseVar = Promise
      .all(typeArrayRef.map(type => type.get()))
      .then(types => {
        const typeList = types.map(type => type.data().name).join(' ');
        return typeList;
      });

    promiseVar.then(type => {
        console.log("Inside the then of promiseVar", type);
    });
};

首先,我们创建一个 promise 列表并等待所有 promise 得到解决。准备就绪后,types 是所有响应的列表。链接 .then 使 promiseVar 解析所需的结果。我们可以使用 await 关键字使其变得更加简单:

renderTypes = async doc => {
    const typeArrayRef = doc.data().type; // assigning the array of documentRefs
    console.log("total elements in types array is ", typeArrayRef.length);

    const types = await Promise.all(typeArrayRef.map(type => type.get()));
    const typeList = types.map(type => type.data().name).join(' ');

    // Not really _inside_ now.
    console.log("Inside the then of promiseVar", typeList);
};

关于javascript - 在 promise 内部,我想将值(该值本身来自另一个 promise )分配给将在该 promise 之外使用的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56819525/

相关文章:

javascript从aws lambda查询dynamodb中的最后一项

ios - swift firebase 迭代每个快照值以更新/设置一个值

javascript - 在 Node JS 中使用 Promise

javascript - 如何避免在浏览器 JavaScript 库中包含冗余的 Promise 实现?

javascript - 如何使用 Meteor Promise 调用 3 个电话

javascript - 使用 Alpine JS 切换元素与类?

javascript - 如何在滚动时使这些 tagHovers 的位置靠近标签并且 tagHover 具有固定位置?

javascript - 使用 CSJS/SSJS 根据范围变量的值自动按下按钮

android - 通知 ViewModel 模型更新?

android - 是否可以重置 Google Analytics for Firebase?