javascript - Redux saga 执行多个 HTTP 请求
问题描述
我如何在 redux saga 中为此有效负载执行多个 http 请求:
[
{
"product_ids": [
"e331e78b-e954-4de3-9bb3-80827b0d0741"
],
"body": {
"command": "request",
"data": {
"api_key": "errtrt4i548",
"api_username": "xxxx",
"vendor_type": 1,
"from": {
"from_description": ""
},
"to": {
"to_name": "Fat Rain Films",
"to_lat": 36.77254990000006,
"to_long": -1.2711643,
"to_description": ""
}
}
}
},
{
"product_ids": [
"9331e78b-e954-4de3-9bb3-80827b0d0741"
],
"body": {
"command": "request",
"data": {
"api_key": "errtrt4i548",
"api_username": "xxxx",
"vendor_type": 1,
"from": {
"from_description": ""
},
"to": {
"to_name": "Fat Rain Films",
"to_lat": 36.77254990000006,
"to_long": -1.2711643,
"to_description": ""
}
}
}
}
]
我的传奇代码是:
export function* getQoute({ qoute }) {
yield put(updateNetworkStatus(true));
const headers = {
method: 'POST',
// credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(qoute),
};
const total = 0;
try {
const req = yield call(
request,
`${API_BASE}/shippings/shipping/initiate_delivery_sendy/`,
headers,
);
console.log(req);
// total += req.
} catch (err) {
console.log(err.message);
//yield put(updateLoadingStatus(false));
}
}
我遇到的挑战是找到一种方法来使用我的有效负载中的数据调用我的 api。即在同一个传奇或动作中调用 api 2 次或与我的 json 有效负载中的对象数量一样多。
解决方案
对于您的情况,您可以遍历 json 数组并分派一个操作来调用您的 saga,并将每个对象作为有效负载。
假设我有一个数组 payloads[2] = {obj1, obj2}。然后做
var i;
for (i = 0; i < payloads.length; i++) {
yield put({type: YOUR_ACTION_TYPE_FOR_SAGA, payload: payloads[i]});
}
推荐阅读
- sorting - 使用特定列,输出在文本文件中出现 3 次的行
- node.js - 如何在 MongoDB(猫鼬)中填充没有 ref 的数组字段?
- lua - 从表中删除项目时,如何避免在 Lua 中创建零引用?
- javascript - 验证数组中的值是否相同或不同
- sql - 如何使用 postgresql 获取 json 对象作为列值?
- mysql - 是否可以绕过 MySQL Azure 的限制?
- java - 如何查看从未来对象执行的线程(名称)
- google-cloud-platform - 检查 Google Cloud API 和服务错误日志
- python - 什么 Cygwin 包允许我调试 Python 代码?
- javascript - 在没有ajax的情况下获取并发送一个Json文件(拖放)到服务器