0

I am trying to keep my response url and the response body for further processing. if I return res.json() like I normally do, then I lose the res.url value.

But if I add code to get the res.url, then I'm having trouble getting my res.json() promise to resolve.

My last attempt was to try to make an async/await function for the res.json() but that isn't working for me either:

 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;    
    };
ThomasRones
  • 657
  • 8
  • 29
  • 1
    Here's a list of your various options: [How to chain and share prior results with promises](https://stackoverflow.com/questions/28714298/how-to-chain-and-share-prior-results-with-promises/28714863#28714863). – jfriend00 Jun 14 '20 at 16:38

2 Answers2

1

Try just making the first then() callback async then you can await 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);
});

Note you need to add additional error handling yourself

charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

If you want to achieve this without async/await keywords, you may use Promise.all to return an array of promises and non-promises:

fetch(url, options)
  .then(res => Promise.all([res.url, res.json()]))
  .then(([url, obj]) => {
    console.log(url);
    console.log(obj);
  });

The Promise.all() method returns a single Promise that fulfills when the iterable contains promises that have been fulfilled and non-promises that have been returned. MDN

or, chain the json() promise while res is still in the same scope:

fetch(url, options)
  .then(res => res.json().then(obj => [res.url, obj])) 
  .then(([url, obj]) => {
    console.log(url);
    console.log(obj);
  });

If you want to achieve this with async/await keywords:

// These must be used inside an async function.

const res = await fetch(url, options)
const obj = await res.json();
const url = res.url;

There are probably more ways to do it (including @charlietfl's answer). Try to understand them and pick one that suits your style. JavaScript is fun!

hangindev.com
  • 4,573
  • 12
  • 28