最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - fetch() call not returning any data - Stack Overflow

programmeradmin2浏览0评论

I'm having a problem with my fetch() call not working correctly. I have a recursion method that calls itself within this function, but once it passes the if statement, the data itself is not being resolved to the .then() call below. I would like to keep the recursion method within this function. Because the system that this function is calling will change the data.result to a different result that is not null. I just don't know when that will happen, hence that is why I'm using the recursion method.

var someToken = "actually token";

function getResult(getToken) {
  return new Promise((resolve, reject) => {
    fetch(url, {
      headers: {
        "Authorization": something,
        "Jenkins-Crumb": getToken
      },
      redirect: 'follow',

    }).then(response => {
      return response.json()

    }).then(data => {

      if (data.result == null) {
        console.log('retrieving data')
        getResult(getToken)
      } else if (data.result == "SUCCESS") {
        console.log('success')
        resolve(data)
      }

    }).catch(err => {
      reject(err)
    })
  })
}

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

I'm having a problem with my fetch() call not working correctly. I have a recursion method that calls itself within this function, but once it passes the if statement, the data itself is not being resolved to the .then() call below. I would like to keep the recursion method within this function. Because the system that this function is calling will change the data.result to a different result that is not null. I just don't know when that will happen, hence that is why I'm using the recursion method.

var someToken = "actually token";

function getResult(getToken) {
  return new Promise((resolve, reject) => {
    fetch(url, {
      headers: {
        "Authorization": something,
        "Jenkins-Crumb": getToken
      },
      redirect: 'follow',

    }).then(response => {
      return response.json()

    }).then(data => {

      if (data.result == null) {
        console.log('retrieving data')
        getResult(getToken)
      } else if (data.result == "SUCCESS") {
        console.log('success')
        resolve(data)
      }

    }).catch(err => {
      reject(err)
    })
  })
}

getResult(someToken).then(data => {
  console.log(data)
}).catch(err => console.log(err))
Share Improve this question edited Mar 15, 2022 at 9:32 VLAZ 29.1k9 gold badges63 silver badges84 bronze badges asked Jan 31, 2020 at 22:38 dacDdacD 251 gold badge2 silver badges4 bronze badges 4
  • 4 You need return getResult(getToken) – Barmar Commented Jan 31, 2020 at 22:41
  • This might be a duplicate of stackoverflow./questions/27691547/… but I'm not sure if that's right for async code. – Barmar Commented Jan 31, 2020 at 22:43
  • 2 Returning the recursive getResult alone wouldn't be enough because he's using the explicit Promise construction antipattern – CertainPerformance Commented Jan 31, 2020 at 22:43
  • Yeah, I had a feeling it wasn't so simple. – Barmar Commented Jan 31, 2020 at 22:49
Add a ment  | 

2 Answers 2

Reset to default 3

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))

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 enpass 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'');
发布评论

评论列表(0)

  1. 暂无评论