javascript - 链式 promise 并装饰对象

标签 javascript node.js express promise fetch-api

我试图理解 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/

相关文章:

node.js - "message": "ENOENT: no such file or directory, open ' E:\\astrology\\utils\\uploads\\1600798534862qf. PNG '"

ios - 第一次没有收到推送通知

node.js - JSON 中位置 0 处出现意外标记 u - 将文件中的 JSON 字符串数据解析到 Web 服务器时

javascript - 如何将函数转换为 async.each 函数

javascript - NodeJS (Windows) - 语法错误 : missing X

javascript - 位置为 :sticky element in iOS 的可滚动 iFrame

javascript - 添加新输入后不工作类 .numeric。我该怎么办?

node.js - 如何在nodejs中使用多线程或多进程

javascript - 根据设备的大小激活图像 slider

javascript - jQuery 在一定数量的匹配元素后切换显示/隐藏元素