javascript - 基于 GET 请求数组的 POST 请求
问题描述
我有一系列客户和地址端点 URL,如下所示
customerArray = [
{name:customer1, id: 1, address: {streetName: '123 lane'}},
{name:customer2, id: 2, address: {streetName: 'xyz lane'}},
{name:customer3, id: 3, address: {streetName: 'abc lane'}}
]
URL = 'id/addresses'
如果我们得到空数组作为响应,则对 URL 的 GET 请求将返回基于客户 ID 的地址数组,然后我们需要为该 ID 添加来自“customerArray”的地址
// This is what I am doing to meet the requirement - seems this is not the right approach. Please help me to fix this
customerArray.forEach((customer) => {
const getObj = {
url: `${customer.id}/addresses`,
method: GET
};
axios(getObj)
.then((getResult) => {
if (getResult.length === 0) {
const postObj = {
url: `${customer.id}/addresses`,
method: POST,
data: customer.address
};
axios(postObj)
.then((postResult) => {
// I am not sure what to do here - I leaving blank so iteration will continue
})
.catch((err) => {
res.status(400).json(err);
});
}
})
.catch((err) => {
res.status(400).json(err);
});
});
请帮我修复它
解决方案
我想你不知道如何获得最终数据。基本上,您应该将您的承诺放入一个数组中,然后Promise.all
等待所有承诺完成。
如果有问题请评论。希望这可以帮助
const promises = customerArray.map((customer) => {
const getObj = {
url: `${customer.id}/addresses`,
method: GET
};
return axios(getObj)
.then((getResult) => {
if (getResult.length === 0) {
return {
url: `${customer.id}/addresses`,
method: POST,
data: customer.address
};
}
return null;
})
.then((postObj) => {
if (postObj) {
return axios(postObj)
}
return null
})
});
Promise.all(promises)
.then(result => {
// the result is a list of data from axios(postObj)
console.log(result);
res.json(result);
})
.catch((err) => {
res.status(400).json(err);
});
推荐阅读
- algorithm - 从Go中的给定字符串计算句子中的最大单词
- flutter - 如何在 Flutter 中的 IconButton 上添加 tintColor?
- java - 我有一个 mysql 数据库和一个表,我将它编码为 json,当我在浏览器中运行 php 文件时,当我从 android 中获取它时,它的一些不同
- android - 我已经使用 ChannelDescriptor 来获取频道,然后调用 getUnconsumedMessagesCount 但在 twilio 聊天中仍然为 android sdk 获得 0 计数
- r - geom_label 没有相应地缩放以在 Shiny 中绘图
- d3.js - 如何在水平条形图中移动刻度标签?
- python - 掷骰子命令问题
- javascript - D3.json Node.js 服务器的意外令牌
- android - 将 View.GONE 更改为 View.VISIBLE 后以编程方式构建覆盖布局仍然没有得到正确的位置
- reactjs - 动态创建内容反应