简体   繁体   中英

Using JavaScript Fetch Returns Pending Promise

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

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

Because you use async function inside basic func. In your case it better to use:

const getWord = word => { // Created function that will be executed if promise resolve.
  console.log(word);
}

const getOutputWord = difficulty => {

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

  let outputWord = fetchWord(fetchParameters).then(value => {
    getWord(value); // pass value of promis
  });
}


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

getOutputWord(3) // will execute getWord and return result in console

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM