gpt4 book ai didi

javascript - 通过 Promise.all 回调几个 API Endpoint 来调度 Redux Action

转载 作者:行者123 更新时间:2023-12-02 22:59:20 25 4
gpt4 key购买 nike

我必须从多个端点获取多个数据,然后合并为单个数据,该数据将发送到reducer,然后我得到Promise.all,获取多个api数据然后合并,我的问题是,如何检测哪个是失败,哪个是成功获取?然后哪个成功仍然发送到reducer,哪个失败发送失败消息

我使用ReactJS,Redux和Redux Thunk,当所有端点都给出成功回调时,所有数据都已发送,但是当其中一个端点失败时,它只会抛出一个来自端点之一的错误

我做了什么:


const chartUrl = [
requestAPI('GET', 'endpoint/a', 2).then(res => res.json()),
requestAPI('GET', 'endpoint/b', 2).then(res => res.json()),
requestAPI('GET', 'endpoint/c', 2).then(res => res.json()),
requestAPI('GET', 'endpoint/d', 2).then(res => res.json()),
requestAPI('GET', 'endpoint/e', 2).then(res => res.json()), // this endpoint fail
requestAPI('GET', 'endpoint/f', 2).then(res => res.json()),
requestAPI('GET', 'endpoint/g', 2).then(res => res.json())
];


let chartObj = {
dataChart: {}
};
Promise.all(chartUrl)
.then(storeData => {
let mergedData = storeData.reduce((prev, cur) => {
prev[cur.message] = cur;
return prev;
}, {});
Object.assign(chartObj.dataChart, mergedData);
// Make detection which code=200 and success=true then dispatch to fetched_chart reducer, but when code != 200 and success=false then dispatch to fail_chart reducer
console.log(chartObj);
})
.catch(err => {
//when server has fail then dispatch to error_fetch_chart reducer
return err;
})

输出:

http://web.data.net/api/v1/endpoint/interaction 500 (Internal Server Error)

我期望这样的输出:

{
dataChart:
{
a: {
code: 200,
success: true
data: chartA
},
b: {
code: 200,
success: true
data: chartB
},
c: {
code: 200,
success: true
data: chartC
},
d: {
code: 200,
success: true
data: chartD
},
e: { //error callback
message: '500 (Internal Server Error)'
}
...
}
}

最佳答案

编辑:如果你想在失败时中止,那么你可以捕获并抛出 John points out在下面的评论中。

如果您在每个请求上都遇到拒绝,则当单个请求失败时,Promise.all 不会拒绝。

// util for invoking the requestAPI, capturing the path in rejection
const req = (path, arg) => requestAPI('GET', path, arg)
.then(req.json())
.catch(e => ({ error: e, path, arg}))

const chartUrl = [
req('endpoint/a', 2),
req('endpoint/b', 2),
// etc.
];

那么你可以这样做:

Promise.all(chartUrl)
.then(results => results.map((r, index) => {
if (r.error) {
// deal with failed individual request
console.error(`request for ${r.path} failed.`)
}
else {
// do something with successful result
}
})
)

关于javascript - 通过 Promise.all 回调几个 API Endpoint 来调度 Redux Action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57847291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com