使用Fetch API发送多个请求,等待它们完成后再执行另一个代码



我有太多的获取api请求和之后的一些代码。我希望Fetch API异步发送请求,但在执行下一个代码之前等待它们的结果。

代码示例:

fetch(url, {method: 'post', body: someData}).then(response => response.json()).then(data => { if(data.STATUS === 'SUCCESSFUL'){ //some code here } });
fetch(url, {method: 'post', body: someData}).then(response => response.json()).then(data => { if(data.STATUS === 'SUCCESSFUL'){ //some code here } });
fetch(url, {method: 'post', body: someData}).then(response => response.json()).then(data => { if(data.STATUS === 'SUCCESSFUL'){ //some code here } });
//some code to run after above requests processing.

相同的多个提取请求。

您可以使用Promise.all()

Promise.all([
fetch(url, {method: 'post', body: someData}), // first fetch
fetch(url, {method: 'post', body: someData}), // second fetch
...
]).then((data) => {
const [firstFetchResult, secondFetchResult, ...] = data;
// data processing
}).then(() => {
// some code to run after above requests processing.
})

如果每个提取结果都有一些自定义逻辑,那么可以为自定义函数使用一些映射。在本例中,映射基于map()索引(回调的第二个参数(:

// Some functions map - first custom functions for first fetch ect;
const FM_MAP = [
(data) => data.substring(40, 50).replace('a', 'b'),
(data) => data.substring(1, 10),
(data) => [...data.substring(25, 30)].join('-_-')
]
Promise.all([
fetch('google.com'),
fetch('google.com'),
fetch('google.com')
]).then((responses) => Promise.all(
// you can work with responses just like with regular arrays
responses
.map((response, index) => response.text().then((data) => {
// custom functions for every data result
console.log(FM_MAP[index](data))
}))
))

相关内容

最新更新