【问题标题】:How to handle a Promise into an array? [duplicate]如何将 Promise 处理成数组? [复制]
【发布时间】:2022-02-10 02:27:54
【问题描述】:

我在处理从getPostedPlaces() 返回的 Promise 时遇到问题。当我运行getAll() 时,它会打印出如下所示的数组。该数组似乎是正确的,但我如何让getAll() 函数返回一个实际的数组。我只能打印它,但我不能返回数组本身。我也尝试将数组内的对象推送到数组上,但它返回空。令人沮丧。

const getPostedPlaces = async () => {
    const querySnapshot = await getDocs(collection(db, "posted_places"));
    const newSnapshot = querySnapshot.docs.map(doc => {
        let newDoc = doc.data();
        newDoc.id = doc.id;
        return newDoc;
    });
    return newSnapshot;
}


const getAll = () => {
    getPostedPlaces().then(res => console.log(res))
}

数组:

Array [
      Object {
        "active": true,
        "category": Array [
          "tøj",
          "møbler",
        ],
        "email": "bar@gmail.com",
        "house_nr": 1,
        "id": "i3juWf6Rj4OPBoKAjkBD",
        "location": Object {
          "latitude": 55.69718057,
          "longitude": 12.52470763,
        },
        "price_interval": Array [
          100,
          700,
        ],
        "street_name": "Hvidkildevej",
        "time_end_actual": "",
        "time_end_expected": "Sat Feb 05 2022 18:00:00 GMT+0100 (CET)",
        "time_start": "Sat Feb 05 2022 09:00:00 GMT+0100 (CET)",
        "zip_code": 2400,
      },
    ]

【问题讨论】:

  • 您的意思是要从.then 延续从getAll 方法返回res 参数吗?如果是这样,您需要返回一个承诺;在承诺完成之前,你不能返回承诺的结果。
  • getAll 不返回任何内容。
  • 我只想最终拥有一个数组。我不在乎它在哪里返回。
  • const getAll = async () => { const result = await getPostedPlaces() // 这是你的结果 }
  • 更多是关于如何将Promise变成数组的问题。

标签: javascript arrays reactjs async-await es6-promise


【解决方案1】:

由于您使用的是{},因此您需要添加退货

const getAll = async () => {
    // since you use {} you need to use return below
    return getPostedPlaces().then(res => {
      console.log(res)
      return res; //you need to return res here.
    })
}

那么当你使用getAll时,它必须是

await getAll()

不需要return 的例子是你不使用{}

const getAll = async() => getPostedPlaces()

【讨论】:

  • 是的,当我写一个内部有await 的函数时,我正在写这个。我已经纠正了。感谢您指出。但是,在涉及函数时编写 async 是一个好习惯。让功能更加明显。
猜你喜欢
  • 2011-05-09
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多