首页 > 解决方案 > 如何通过 .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;    
    };

标签: javascriptpromisefetch

解决方案


尝试只进行第一个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);
});

请注意,您需要自己添加额外的错误处理


推荐阅读