【问题标题】:React Firebase async return of IDsReact Firebase 异步返回 ID
【发布时间】:2023-03-19 02:03:01
【问题描述】:

我有一个名为 booking app 的公司项目,我正在尝试在 firebase 中添加“服务”。

添加服务后,我想检索他们的 ID 并将它们作为数组添加到“公司”,如果添加“服务”,则返回第一个函数。

const addedServicesIDs = await addServices(arrayOfServices);

await addCompany(newCompany, addedServicesIDs);

服务已成功添加,但我无法检索存储在 addServices 函数中的 ID 并将它们作为数组返回。

console.log 工作正常。

    async function addServices(props) {
  const arrayOfServices = props;
  const arrayOfServicesID = [];

  arrayOfServices.forEach(async (service, index) => {
    console.log(service);
    await db
      .collection("services")
      .add({
        serviceName: service.serviceDetails.serviceName,
        description: service.serviceDetails.description,
        duration: service.serviceDetails.duration,
        price: service.serviceDetails.price,
        capacity: service.serviceDetails.capacity,
        workingDays: service.serviceDayWorking,
      })
      .then((docRef) => {
        arrayOfServicesID[index] = docRef.id;
        console.log("Written Service with ID of ", docRef.id);
      });
  });
 
  return arrayOfServicesID;
}

也许我没有理解异步功能, 非常感谢您的帮助!

【问题讨论】:

  • 尝试删除 async/await 并保留 then() 符号。有帮助吗?

标签: reactjs firebase asynchronous google-cloud-firestore async-await


【解决方案1】:

我终于找到了解决办法。

  1. 我使用了const 而不是var,这就是我的变量没有更新的原因。
var AddedServicesIDs = [];
  1. 我已经重构了我的代码
export async function addServices(props) {
      const doc_ref = await db.collection("services").add({
        serviceName: props.serviceDetails.serviceName,
        description: props.serviceDetails.description,
        duration: props.serviceDetails.duration,
        price: props.serviceDetails.price,
        capacity: props.serviceDetails.capacity,
        workingDays: props.serviceDayWorking,
      });
    
      return doc_ref.id;
    }

for (const service of arrayOfServices) {
    const extractedID = await addServices(service);
      AddedServicesIDs.push(extractedID);
    }

【讨论】:

    猜你喜欢
    • 2019-02-01
    • 2020-03-21
    • 2016-02-14
    • 2017-01-14
    • 2019-01-08
    • 2021-12-23
    • 2017-07-06
    • 1970-01-01
    • 2018-10-10
    相关资源
    最近更新 更多