并行解析多个 fetch 请求

vin*_*sty 5 reactjs react-native

我正在尝试在react-native. 但我没有得到预期的响应数据。我错误地整合了什么?

async componentDidMount() {
    try {
        let [res1, res2] = await Promise.all([
            fetch(apiUrl1),
            fetch(apiUrl2),
        ]);

        console.warn(res1);
        console.warn(res2);
    }
    catch(err) {
        console.warn(err);
    };
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的奇怪回应。

{"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "4", "offset": 0, "size": 661}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "", "offset": 0, "size": 661}}, "headers": {"map": {"cache-control": "no-store, no-cache, must-revalidate", "cf-cache-status": "DYNAMIC", "cf-ray": "5", "content-type": "application/json; charset=utf-8", "date": "Thu, 09 Jan 2020 12:15:40 GMT", "expect-ct": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"", "expires": "", "pragma": "no-cache", "server": "cloudflare", "set-cookie": "ci_session=; expires=; Max-Age=7200; path=/; HttpOnly"}}, "ok": true, "status": 200, "statusText": undefined, "type": "default", "url": "apiurl"}
Run Code Online (Sandbox Code Playgroud)

Pab*_* H. 23

我有点晚了,但向您展示如何仅使用Promise.all和async/执行多个请求并等待它们的解决似乎是个好主意await。

\n

下面的代码还展示了如何正确处理多个 HTTP 请求的错误。我提到这一点是因为由于fetch()工作方式的原因,catch当发生 HTTP 错误时,代码块将不会被执行:

\n
\n

fetch()仅当遇到网络错误时(通常是存在权限问题或类似问题时),promise 才会被拒绝。A\n fetch()Promise 不会拒绝 HTTP 错误(404 等)。相反,then()处理程序必须检查Response.ok和/或Response.status\n属性。\xe2\x80\x93 取自MDN

\n
\n

\r\n
\r\n
(async () => {\n  try {\n    const urls = [\n      "https://api.chucknorris.io/jokes/random",\n      "https://api.chucknorris.io/jokes/random",\n      "https://api.chucknorris.io/jokes/random",\n      "https://api.chucknorris.io/jokes/random",\n    ];\n\n    const requests = urls.map((url) => fetch(url));\n    const responses = await Promise.all(requests);\n    const errors = responses.filter((response) => !response.ok);\n\n    if (errors.length > 0) {\n      throw errors.map((response) => Error(response.statusText));\n    }\n\n    const json = responses.map((response) => response.json());\n    const data = await Promise.all(json);\n\n    data.forEach((datum) => console.log(datum));\n  }\n  catch (errors) {\n    errors.forEach((error) => console.error(error));\n  }\n})();
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

为了清楚起见,我还为您提供了一个等效方法then():

\n

\r\n
\r\n
(() => {\n  const urls = [\n    "https://api.chucknorris.io/jokes/random",\n    "https://api.chucknorris.io/jokes/random",\n    "https://api.chucknorris.io/jokes/random",\n    "https://api.chucknorris.io/jokes/random",\n  ];\n  const requests = urls.map((url) => fetch(url));\n\n  Promise.all(requests)\n    .then((responses) => {\n      const errors = responses.filter((response) => !response.ok);\n\n      if (errors.length > 0) {\n        throw errors.map((response) => Error(response.statusText));\n      }\n\n      const json = responses.map((response) => response.json());\n      return Promise.all(json);\n    })\n    .then((data) => {\n      data.forEach((datum) => console.log(datum));\n    })\n    .catch((errors) => {\n      errors.forEach((error) => console.error(error));\n    });\n})();
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n


小智 5

Promise.all() 方法返回一个 Promise,当作为可迭代对象传递的所有 Promise 都已实现或者可迭代对象不包含 Promise 时,该 Promise 就会实现。它以第一个拒绝的承诺为理由拒绝。- 来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

您刚刚所做的是将 Promise 解析分配给变量,然后 console.log 它。这不是你想要的。像这样的东西应该给出你想要的结果?

async componentDidMount() {
    try {
        await Promise.all([
            fetch(apiUrl1),
            fetch(apiUrl2),
        ]).then([res1, res2] => {    
            console.warn(res1);
            console.warn(res2); 
        });
    }
    catch(err) {
        console.warn(err);
    };
}
Run Code Online (Sandbox Code Playgroud)


Vip*_*dav 5

如果您的回复是 json,请使用以下代码

 let [res1, res2] = await Promise.all([
            fetch(apiUrl1).then(response => response.json()),
            fetch(apiUrl2).then(response => response.json()),
        ]);

Run Code Online (Sandbox Code Playgroud)