【问题标题】:Save the value of a response in an extern variable at the [duplicate]将响应的值保存在 [重复] 的外部变量中
【发布时间】:2022-01-07 08:10:17
【问题描述】:

我是 Promise 的新手,想知道如何将响应的结果存储在外部变量中

var obj;
fetch("https://api.nvidia.partners/edge/product/search?page=1&limit=9&locale=fr-fr&category=GPU&gpu=RTX%203070&manufacturer=NVIDIA&manufacturer_filter=NVIDIA~1,ASUS~1,EVGA~3,GIGABYTE~2,MSI~1,PNY~0,ZOTAC~0")
    .then(res => res.json())
    .then(data => obj = data.searchedProducts.featuredProduct.retailers[0].purchaseLink)
    .then(() => console.log(obj))

console.log(obj);

我设法在承诺中显示响应,但不在外部

the undefined value comes from the second console.log

感谢您花时间阅读我的请求 :)

【问题讨论】:

  • 您的第二个“console.log(obj)”在设置 obj 的值之前执行,因此在记录时它仍然未设置

标签: javascript promise fetch-api


【解决方案1】:

你能做的就是等待它:

const res = await fetch("https://api.nvidia.partners/edge/product/search?page=1&limit=9&locale=fr-fr&category=GPU&gpu=RTX%203070&manufacturer=NVIDIA&manufacturer_filter=NVIDIA~1,ASUS~1,EVGA~3,GIGABYTE~2,MSI~1,PNY~0,ZOTAC~0");
const data = await res.json();
const obj = data.searchedProducts.featuredProduct.retailers[0].purchaseLink;
console.log(obj);

那你可以console.log()它。

【讨论】:

  • 避免使用Promise constructor antipattern,这里没有什么可承诺的!如果您的实际答案是使用async/await,请明确说明并实际使用它来代替every then
  • @Bergi 感谢您的链接。我学到了一些东西!谢谢
  • @Bergi 我更新了代码
  • 谢谢,这样更好,但在访问data.searchedProducts.… 之前,您仍应使用const res = await …const data = await …
猜你喜欢
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-13
  • 1970-01-01
  • 2014-07-07
相关资源
最近更新 更多