首页 > 解决方案 > 如何从 .t​​hen 承诺中访问值?

问题描述

我正在执行以下操作:

fetch("someurl")
.then(data => {return data.json()})
.then(resp => console.log(resp));

现在,通常我从 .then 函数中对 resp 进行操作,但是是否可以将 resp 分配给一个变量,或者至少将它存储在某个地方以便我可以在另一个函数中检索它?

例子:


let thedata;

fetch(URL).then(res => {
    return res.json()
}).then(data => {
    console.log(data[0].category); //helloWorld
    thedata = data[0].category 

});


console.log(thedata);

function printsomething()
{return thedata}

现在数据将是未定义的,如果没有在函数内部,我就不能使用函数 printsomething .then()

这就是我的问题的意思。

标签: javascript

解决方案


通过将fetchPromise 链分配给一个变量,您可以.then从多个位置调用该变量,尽管这样做有点奇怪:

const prom = fetch("someurl")
  .then(res => res.json());
prom.then((data) => {
  console.log(data);
});
// Separately:
prom.then((data) => {
  console.log(data.foo);
});

在大多数情况下,使用将所有内容放在单个.thenafter中的原始策略会更有意义res.json()


推荐阅读