javascript - 如何通过 .then() 链保留响应 url 和响应正文?
问题描述
我正在尝试保留我的响应网址和响应正文以供进一步处理。如果我像往常一样返回 res.json(),那么我会丢失 res.url 值。
但是,如果我添加代码来获取 res.url,那么我很难让我的 res.json() 承诺得到解决。
我最后一次尝试是尝试为 res.json() 创建一个 async/await 函数,但这对我也不起作用:
fetch(url, options).then((res)=>{
let obj = getJSON(res);
let profileUrn = res.url.match(/(?<=urn%3Ali%3Afsd_profile%3A).+(?=&)/)[0];
let rep = {
profileUrn,
obj
};
return rep;
}
).then((data)=>{
console.log(data.profileUrn);
console.log(data.obj);
}
);
async function getJSON(res){
let data = await res.json();
return data;
};
解决方案
尝试只进行第一个then()
回调async
,然后您可以等待 res.json()
fetch(url, options).then(async (res)=>{
// ^^^ async
let obj = await res.json();
// ^^ await the json promise
let profileUrn = res.url.match(/(?<=urn%3Ali%3Afsd_profile%3A).+(?=&)/)[0];
let rep = {
profileUrn,
obj
};
return rep;
}).then((data)=>{
console.log(data.profileUrn);
console.log(data.obj);
});
请注意,您需要自己添加额外的错误处理
推荐阅读
- c# - 为什么对象和集合初始值设定项的组合使用 Add 方法?
- scala - 无法更改 Spark foreach 函数体内的全局变量
- html - 如何缩进列表和子列表菜单?
- json - 当预期的字符串数组返回对象时,Gson 抛出异常
- python - 在python中循环到邻接矩阵
- apache-spark - 如何使用 Spark Scala 加入 3 个 RDD
- android - 无法初始化条码检测器
- list - Python,FOR 循环 - 创建列表
- jquery - 使用 Bootstrap 工具栏按钮按列过滤 HTML 表格
- acumatica - acumatica 和 zpl 标签打印