【问题标题】:new promise inside a async function in order to grab the value outside of the async function异步函数内部的新承诺,以获取异步函数外部的值
【发布时间】:2021-01-25 03:47:38
【问题描述】:

我正在一个异步函数中返回一个新的 Promis,该函数正在向 api 发出请求,我可以在函数内部很好地控制台记录来自 api 的请求。但是当我尝试解决同一行时,我安慰document.sold 它不起作用。我希望checkPriceId 变量返回一个我可以用.then 捕获的promise,但这似乎不起作用。我也尝试在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()

【问题讨论】:

  • 您需要致电checkPriceIdcheckPriceId().then(...)
  • 你不想在每个文档上调用resolve,顺便说一句,你可能想用documents.sold的数组调用resolve(同上resolve(documents.map(x => x.sold)))但首先你可以关注@ blex指令

标签: javascript async-await es6-promise


【解决方案1】:

Why use the Promise constructor at all? client.fetch 已经返回了一个 Promise,并且您也在一个异步函数中,该函数也返回了一个 Promise。假设所有文档都有一个.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 参数,因为它没有被使用。

【讨论】:

    【解决方案2】:

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

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

    由于混合 Promise 和 async 的方式可能会变得冗长且不透明,我建议您在这里只使用 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
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-08
      • 2016-05-22
      • 2018-12-24
      • 2022-01-26
      • 2018-09-07
      • 2018-11-17
      • 2021-07-16
      相关资源
      最近更新 更多