Как правильно организовать запросы к API
Получаю все данные по пользователю из разных методов в один объект:
let client = {};
apiGetClient()
.then((response) => {
client = { ...client, ...response.data };
apiGetClientInfo().then(response => {
client = { ...client, ...response.data };
apiClientIdentities().then(response => {
client = { ...client, ...response.data };
apiClientAddresses().then(response => {
client = { ...client, ...response.data };
apiClientGuarantors().then(response => {
client = { ...client, ...response.data };
apiClientWork().then(response => {
client = { ...client, ...response.data }
apiClientContacts().then(response => {
client = { ...client, ...response.data }
console.log(client, "Client")
})
})
})
})
})
})
})
Я не понимаю как это переделать правильно на цепочку промисов,
apiGetClient()
.then((response) => {
return client = { ...client, ...response.data };
})
.then((client) => {
apiGetClientInfo().then(response => {
client = { ...client, ...response.data };
})
})
.then((client) => {
apiClientIdentities().then(response => {
client = { ...client, ...response.data };
})
})
.then((client) => {
apiClientAddresses().then(response => {
client = { ...client, ...response.data };
})
})
.then((client) => {
apiClientGuarantors().then(response => {
client = { ...client, ...response.data };
})
})
.then((client) => {
apiClientWork().then(response => {
client = { ...client, ...response.data }
})
})
.then((client) => {
apiClientContacts().then(response => {
client = { ...client, ...response.data }
})
})
.then((client) => {
console.log(client, "Client")
})
Как я понял должно быть что то вроде этого но как вернуть все в один обьект?
Ответы (2 шт):
Автор решения: prit
→ Ссылка
(async () => {
let resClient = await apiGetClient();
let resClientInfo = await apiGetClientInfo();
let resClientIdenties = await apiClientIdentities();
let respClientAddress = await apiClientAddresses();
let resClientGuarantos = await apiClientGuarantors();
let resClientWork = await apiClientWork();
let resClientContact = await apiClientContacts();
let client = {
...resClient.data,
...resClientInfo.data,
...resClientIdenties.data,
...respClientAddress.data,
...resClientGuarantos.data,
...resClientWork.data,
...resClientContact.data
};
console.log(client, "Client");
})()
Автор решения: Grundy
→ Ссылка
Цепочка нужна там, где следующий запрос зависит от того, что вернет предыдущий.
В данном случае, так как результаты не зависят друг от друга, стоит вообще убрать цепочку и воспользоваться методом Promise.all
let client = {};
Promise.all([
apiGetClient(),
apiGetClientInfo(),
apiClientIdentities(),
apiClientAddresses(),
apiClientGuarantors(),
apiClientWork(),
apiClientContacts()
])
.then(responses => responses.map(r => r.data))
.then(data => Object.assign(client, ...data))
.then(client => console.log(client, "Client"));