javascript - 如何从 .then 承诺中访问值?
问题描述
我正在执行以下操作:
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()
。
这就是我的问题的意思。
解决方案
通过将fetch
Promise 链分配给一个变量,您可以.then
从多个位置调用该变量,尽管这样做有点奇怪:
const prom = fetch("someurl")
.then(res => res.json());
prom.then((data) => {
console.log(data);
});
// Separately:
prom.then((data) => {
console.log(data.foo);
});
在大多数情况下,使用将所有内容放在单个.then
after中的原始策略会更有意义res.json()
。
推荐阅读
- swift - 检查 UITextfield 中十进制输入的有效性
- html - 如何使用自定义 .png-Images 而不是 mat-icons 作为按钮?
- c++ - 有没有办法在参数化构造函数中输入 10 个学生的详细信息,并在 c++ 中使用带有对象数组的成员函数打印它
- excel - 脚本字典性能损失的变体
- reactjs - 如何在反应中使用带有 className 的状态信息?
- javascript - hasOwnProperty 返回 false 但是似乎有属性的对象?
- python - 如何使用 pandas 从我的电影数据框中获取美国排名前 5 的电影类型
- mysql - VB.NET mysqldatareader 漏掉第一行
- python - 用于在 raspberry Pi 上显示的 Python 脚本,while true 会在一段时间后停止
- android - Kotlin 冲突声明:val sinAngle: Float, val sinAngle: Float