为什么 Promise 会有这种表现?

查看 35|回复 0
作者:icoming   
看下面代码,为什么使用“错误的处理”那种情况。明明所有hasStock很快执行完毕并且返回了结果,但是会在判断没货之间,每个判断之间会卡几秒,不是已经有结果了吗。。。
GPT4 说“错误的处理”应该是秒出结果的,它也没搞明白
// 需要订购的产品链接
const productList = [
  "https://xxx",
  "https://xxx",
  "https://xxx"
]
// 是否有货
const hasStock = async (url: string): Promise[b] => {
  const resp = await mAxios.get(url)
  return resp.data.trim() !== ""
}
// 开始订购
const startOrder = async () => {
  const promises = productList.map(u => ({tag: u, promise: hasStock(u)}))
  // 根据是否有货判断购买
  // 正确的处理
  const results = await Promise.allSettled(promises.map(p => p.promise))
  // 错误的处理
  // const results = await Promise.allSettled(promises)
  
  for (const [i, result] of results.entries()) {
    // ...
    // 是否有货,有就订购
    if (!result.value) {
      console.log("无货", promises[i].tag)
      continue
    }
}
您需要登录后才可以回帖 登录 | 立即注册

返回顶部