简体   繁体   English

使用fetch和await打印简单文本。 为什么在异步函数中需要多个等待?

[英]Printing simple text using fetch and await. Why do I need more than one await inside an async function?

I'm trying to do webcrawling using fetch on React Native. 我正在尝试在React Native上使用访存进行网络爬虫。 This is what I'm doing: 这就是我在做什么:

  const response = fetch(
        url,
        {
            body          : post_data ? post_data : undefined, // must match 'Content-Type' header
            cache         : 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            headers       : headers,
            method        : post_data ? 'POST' : 'GET', // *GET, POST, PUT, DELETE, etc.
            redirect      : redirect ? 'follow' : 'manual', // *manual, follow, error. TODO: is manual the right keyword?
            referrer      : 'no-referrer', // *client, no-referrer
        }
    );

    const http   = await response;
    const header = http.headers;
    const html   = http.text();

    console.log(html);

When I print header , I can see the headers. 当我打印header ,可以看到标题。 When I print html , this is what I see: 当我打印html ,这是我看到的:

{ _40: 0, _65: 0, _55: null, _72: null }

What am I possibly doing wrong? 我可能做错了什么? I thought one await was necessary, but if I change to: 我认为有必要等待,但是如果我更改为:

const http   = await response;
const header = await http.headers;
const html   = await http.text();

console.log(html);

then I can see the HTML. 然后我可以看到HTML。 But as I've read, await makes the execution pause and resolves the Promise . 但是,正如我所阅读的, 等待使执行暂停并解决了Promise So why should I need the two extra awaits below await response? 那么,为什么我需要下面等待响应的两个额外等待?

Getting the response is one promise, while reading it's content is a second promise. 获得响应是一个承诺,而阅读内容是第二个承诺。 That's why you need to await twice. 这就是为什么您需要等待两次。

Equivalent without async/await would be: 没有异步/等待的等效项是:

   fetch("/url")
    .then((response) => response.text() /* check response status and etc */)
    .then((response) => console.log(response) /* actual response text /*);

Fetch returns a Response object, which is a stream that does not actually contain the response content . Fetch返回一个Response对象,该对象是实际上不包含响应内容的流 You have to call one of the methods to read the stream and return the actual content. 您必须调用其中一种方法来读取流并返回实际内容。

For example: 例如:

const response = await fetch( /* your parameters */ );
const responseText = await response.text();

Taking a step back, await accepts a promise as its argument. 退后一步, await接受诺言。 Looking at the docs for fetch . 查看文档以fetch fetch() returns a promise. fetch()返回一个promise。 response.headers is not a promise. response.headers不是一个承诺。 response.text() returns a promise. response.text()返回一个承诺。

Given all of that, await response.headers is not necessary, but your other two are. 考虑到所有这些,就没有必要await response.headers ,但是您的另外两个是。

As for why response.text() returns a promise, the critical piece is that the response promise resolves as soon as the request starts getting data back, which is before the response data has already been received. 至于为什么 response.text()返回promise,最关键的一点是, response promise会在请求开始获取数据后立即解决,即已经接收到响应数据之前 This means that await response waits to know "did the server response, and if so with what status code/header , and await response.text()` waits for the actual data that the server sends. 这意味着await response会等待知道服务器响应,如果是,则返回什么状态码/标题, and await response.text()会等待服务器发送的实际数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我需要在其他功能中再次异步/等待? - Why do I need to async/await again in a different function? 在do-while循环中带有await的异步函数 - async function with await fetch inside do-while loop 具有Async / Await的TypeScript和Promise包装器。 如何绑定旧代码? - TypeScript and Promise wrapper with Async/Await. How do I tie in legacy code? 如果我定义了一个异步 function 并在 body 中使用 await,那么在调用 function 时是否需要使用 await? - If I define an async function and use await in the body, do I need to use await when calling the function? 我是否需要检查子异步/等待 function 在父节点中是否成功? - Do I need to check a child async/await function was successful in the parent? 我需要在异步函数中的每个语句之前放置 await 吗? - Do I need to put await before every statement in an async function? 我需要等待我的异步 function,然后返回吗? - Do I need to await my async function, then return? 当异步函数不返回 Promise 时,为什么我需要等待它? - Why do I need to await an async function when it is not supposedly returning a Promise? 为什么我需要使用异步等待在 React 中调用异步 function 而在纯 JS 文件中不需要 - Why do I need to use async await to call a async function in React while it doesn't need in pure JS file 我有 2 个代码片段,一个使用.then().catch,另一个使用 async/await。 两个片段都在做同样的事情吗? - I have 2 snippets of code, one uses .then().catch and the other uses async/await. Are both snippets doing the exact same thing?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM