Using JavaScript Fetch Returns Pending Promise

前提是你 提交于 2021-01-29 07:52:49

问题


I'm fetching text from a Dictionary API and I can't quite figure out why my code returns a pending promise. However logging the value returns the intended text. Here is my code,

const getWord = (difficulty) => {

    const fetchParameters = api + "?difficulty=" + difficulty

    let outputWord = fetchWord(fetchParameters).then(value => {
        console.log(value) // ->Logs intended text
        return value
    })

    return outputWord // -> Returns Pending Promise
}


async function fetchWord(fetchParams) {
        const response = await fetch(fetchParams)
        const text = await response.text()
        return text.split("\n")[1]
}

test = getWord(5)

console.log(test) // Results in Pending Promise


回答1:


Since async functions return a Promise, you need to wait for that promise to resolve before you can use the value

One solution is to wrap your code in an async IIFE

(async () => {
  const getWord = (difficulty) => {

    const fetchParameters = api + "?difficulty=" + difficulty

    let outputWord = fetchWord(fetchParameters).then(value => {
      console.log(value) // ->Logs intended text
      return value
    })

    return outputWord // -> Returns Pending Promise
  }


  async function fetchWord(fetchParams) {
    const response = await fetch(fetchParams);
    const text = await response.text();
    return text.split("\n")[1]
  }

  let test = await getWord(5)
  console.log(test) // Results in correct output
})();

But note: test is still not going to be a value available outside this IIFE

Another solution is to use Promise.then

const getWord = (difficulty) => {

  const fetchParameters = api + "?difficulty=" + difficulty

  let outputWord = fetchWord(fetchParameters).then(value => {
    console.log(value) // ->Logs intended text
    return value
  })

  return outputWord // -> Returns Pending Promise
}


async function fetchWord(fetchParams) {
  const response = await fetch(fetchParams);
  const text = await response.text();
  return text.split("\n")[1]
}

getWord(5).then(test =>
  console.log(test)
);

But, again, value of test is still only available inside the final .then callback

There's just no way to have the result available "synchronously" since asynchronous code returns the value at some unknown time in the future - so you just have to work with asynchrony rather than try to short cut it

To me, it appears you are trying to use the intermediate async function to short circuit asynchrony - which you can't - the above code is over complicated way of doing

const getWord = async (difficulty) => {

  const fetchParameters = api + "?difficulty=" + difficulty;

  const response = await fetch(fetchParameters);
  const text = await response.text();
  return text.split("\n")[1];
};

getWord(5).then(test =>
  console.log(test)
);


来源:https://stackoverflow.com/questions/58228574/using-javascript-fetch-returns-pending-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!