使用JavaScript提取返回待处理的承诺 [英] Using JavaScript Fetch Returns Pending Promise

查看:57
本文介绍了使用JavaScript提取返回待处理的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从Dictionary API中获取文本,但我不太清楚为什么我的代码会返回未决的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

推荐答案

由于 async 函数返回了Promise,因此您需要等待该诺言得以解决,然后才能使用该值

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

一种解决方案是将代码包装在异步IIFE中

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

但是请注意: test 仍然不是该IIFE之外的可用值

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

另一种解决方案是使用Promise.然后

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

但是同样, 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)
);

这篇关于使用JavaScript提取返回待处理的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆