异步函数内的新承诺,以便获取异步函数外部的值

new promise inside a async function in order to grab the value outside of the async function

我正在 return 在异步函数中创建一个新的 Promis,它正在向 api 发出请求,我可以控制台记录来自 api 的请求功能。但是当我尝试解决我安慰 document.sold 的同一行时,它不起作用。我希望 checkPriceId 变量成为 return 一个我可以用 .then 捕获的承诺,但这似乎不起作用。我也尝试在 documents.forEach 循环周围使用 promise.all 无济于事。

如有任何帮助,我们将不胜感激。

这是代码

const checkPriceId = async test => {
      return new Promise((resolve, reject) => {
        const query = `*[_type == "products" && price_id == "${body.price_id}"]`
        client.fetch(query, {}).then(documents => {
          documents.forEach(document => {
            //console.log(document.sold)
            resolve(document.sold)
          })
        })
      })
    }

    checkPriceId.then(test => {
      console.log(test) // does nothing
    })

    console.log(checkPriceId) // just returns a async function

    checkPriceId()

Why use the Promise constructor at allclient.fetch 已经 returns 一个承诺,而且你也在一个异步函数中,它也是 returns 一个承诺。假设所有文档都有一个 .sold,您正试图返回一个数组:

const checkPriceId = async () => {
  const query = `*[_type == "products" && price_id == "${body.price_id}"]`
  const documents = await client.fetch(query, {})
  return documents.map(({ sold }) => sold)
}

checkPriceId.then((soldList) => {
  console.log(soldList)
})

这也删除了 checkPriceIdtest 参数,因为它没有被使用。

正如@blex 提到的那样,您没有在第 13 行调用 checkPriceId。

但是,正如@grodzi 也提到的,您不能 resolve 您的承诺多次。一旦 resolve fn 被调用一次(第 7 行),后续调用将被忽略。

由于混合使用 Promises 和异步的方式可能会冗长且不透明,我建议您在这里使用 async/awiat。这将极大地帮助您提高代码的可读性。

这是一个固定的例子:

const checkPriceId = async (test) => {
  
  const query = `*[_type == "products" && price_id == "${body.price_id}"]`;

  const documents = await client.fetch(query, {}); // this could throw

  return documents.map(document => document.sold);
}

checkPriceId().then(test => {
  console.log(test) // this will log the return value from line 7
})