如何在异步/等待中使用提取? [英] How to use fetch with async/await?

查看:82
本文介绍了如何在异步/等待中使用提取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先说我不是100%肯定这是问题所在,我的意思是使用await和async.

I start by saying that I am not 100% sure this is the problem, I mean using await and async.

这是场景:

我在第一次加载页面时运行此程序,并且运行正常,我得到了data:

I run this when I first load the page, and works fine, I get the data:

    externalContent(url);

    function externalContent(url) {
      fetch(url)
      .then(res => res.json())
      .then(data => {
        ...cool data...
      });
    }

但是我需要能够单击一个按钮,然后使用fetch

But then I need to be able to click a button and re run that function with the fetch

我愿意

    $(".alm-filters--button").on("click", function() {
      externalContent(url);
    }); 

但是当我单击时,它在.then(res => res.json())

But when I click, It gives me an error on .then(res => res.json())

错误说: 未捕获(承诺)TypeError:无法读取未定义的属性'then'

The error says: Uncaught (in promise) TypeError: Cannot read property 'then' of undefined

我尝试过存在异步问题,但是我对使用异步和等待知之甚少,但我尝试过:

I believe there is an asynchronous issue, I tried, but I do not know enough about using async and await, yet I tried:

    async function externalContent(url) {
      await fetch(url)
      .then(res => res.json())
      .then(data => {
         ...cool data...
      });
    }

但是等等,我遇到了同样的错误.

But et, I get the same error.

推荐答案

引用本文应该解决您的问题.也请参见代码段.

Referring to this article should take care of your issue. See the snippet as well.

async function exampleFetch() {
    const response = await fetch('https://reqres.in/api/users/2');
    const json = await response.json();
    console.log(json);
}

exampleFetch()

await替代.then(),因此使用await fetch时,您根本不需要使用.then().

await substitutes for .then(), so when using await fetch, you don't need to use .then() at all.

还有另外两个答案或多或少涉及同一问题:

Here are a couple other answers which deal with more or less the same issue:

1-如何访问异步获取函数的值? [重复]

2-使用Async/Await返回API来获取API的返回值意外]

这篇关于如何在异步/等待中使用提取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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