[Vuejs]-Fetch() call not returning any data

2👍

try using async...await and your code will be much simpler

var someToken = "actually token";

async function getResult(getToken) {
  const resp = await fetch(url, {
    headers: {
      "Authorization": something,
      "Jenkins-Crumb": getToken
    },
    redirect: 'follow',
  });
  const data = await resp.json();
  if (data.result == null) {
    console.log('retrieving data')
    return getResult(getToken)
  } else if (data.result == "SUCCESS") {
    console.log('success')
    return data;
  }
}

getResult(someToken).then(data => {
  console.log(data)
}).catch(err => console.log(err))

3👍

You need to return the recursive call of getResult and avoid the explicit Promise construction antipattern (just return the Promises instead):

function getResult(getToken) {
  return fetch(url, {
    headers: {
      "Authorization": something,
      "Jenkins-Crumb": getToken
    },
    redirect: 'follow',
  })
    .then(response => response.json())
    .then(data => {
      if (data.result == null) {
        console.log('retrieving data');
        return getResult(getToken); // <-----------------------------
      } else if (data.result == "SUCCESS") {
        console.log('success');
        return data; // <-------------------------------------------
      }
      // What if data.result is neither null nor SUCCESS?  <--------
    });
}

getResult(someToken).then(data => {
  console.log(data);
}).catch(err => console.log(err))

Live demo:

const getUrl = () => Math.random() < 0.25 ? 'data:,{"result":"SUCCESS"}' : 'data:,{}';

function getResult(getToken) {
  return fetch(getUrl(), {
    headers: {
      "Authorization": 'something',
      "Jenkins-Crumb": getToken
    },
    redirect: 'follow',
  })
    .then(response => response.json())
    .then(data => {
      if (data.result == null) {
        console.log('retrieving data');
        return getResult(getToken); // <-----------------------------
      } else if (data.result == "SUCCESS") {
        console.log('success');
        return data; // <-------------------------------------------
      }
      // What if data.result is neither null nor SUCCESS?  <--------
    });
}

getResult('someToken').then(data => {
  console.log(data);
}).catch(err => console.log(err))

You should also consider – your if and else ifs at the end of the .then may not encompass all possibilities. What if data.result is neither null nor 'SUCCESS'? Given your current logic, the getResult call will result in data being undefined in the consumer. If there’s a chance of that happening, you might want to throw an error or something in that case.

if (data.result == null) {
  console.log('retrieving data')
  return getResult(getToken) // <-----------------------
} else if (data.result == "SUCCESS") {
  console.log('success')
  return data; // <-----------------------
}
throw new Error('data.result is neither null nor 'SUCCESS'');

Leave a comment