gpt4 book ai didi

javascript - 链式 promise 并装饰对象

转载 作者:行者123 更新时间:2023-12-01 02:00:54 28 4
gpt4 key购买 nike

我试图理解 promise ,我需要链接它们并装饰来自不同端点的对象宽度数据。

例如:

我的 Node-express 应用程序中有这个

//controller.js
export const getItem = (req, res) => {
ItemService.getItem(req.params.id).then(function(item) {
return res.json({ 'success': true, 'message': 'Item found successfully', 'item': item});
}).catch(function(result) {
return res.json({ 'success': false, 'errorMessage': 'Ups!' });
});
};

//itemService.js
export const getItem = function(id){
return new Promise(function(resolve, reject) {
fetch(apiUrls.getItem(id))
.then(response => {
if(response.ok){
response.json().then(data => {
resolve(data);
})
} else {
reject(response.err);
}
});
});
};

所以我想要完成的是在解析语句之前装饰数据。事实上,我想对不同的 API 进行其他获取,并使用该响应中的数据来装饰我首先讨论的数据。我将编写一些伪代码:

fetch (api1)
responseApi1 //{id: 123, name: 'Mike'}
fetch (api2)
responseApi2
responseApi1.description = responseApi2.description
responseApi1.address = responseApi2.address

return responseApi1 //responseApi1 decorated width responseApi2

//Controller
return res.json({ 'success': true, 'message': 'Item found successfully', 'item': responseApi1});

我根本不理解 promise ,无法创建这一 promise 链并通过此 promise 装饰一个对象并返回它。

最佳答案

回答您的“伪代码”示例(假设两个 api 都返回 JSON)

return fetch (api1)
.then(res => res.json())
.then(responseApi1 => fetch(api2)
.then(res => res.json())
.then(({descritpion, address}) => ({...responseApi1, description, address}))
)
.then(result => {
//result is responseApi1 decorated width responseApi2
});

或者,如果 api2 不依赖于 api1 的结果(从伪代码中不清楚)

return Promise.all(fetch(api1).then(res => res.json()), fetch(api2).then(res => res.json()))
.then((responseApi1, {descritpion, address}) => ({...responseApi1, description, address}));

尽管如此,我不确定伪代码中的 controller 部分的含义 - 完全没有意义,就像您根本拥有它一样

关于javascript - 链式 promise 并装饰对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50594373/

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