使用另一个提取从提取内部更改 json 对象 属性

Changing json object property from inside fetch using another fetch

我正在使用 REST 国家/地区 API(已给出 link)创建 Web 应用程序 https://restcountries.com/.
API 给出 json 和 属性 borders,这是一个字符串数组,给出了边界国家的 cca3。我也想知道这些国家的名称,因此我再次请求提供该数据。到目前为止,这就是我想出的。但是,从第一个请求返回的 json 永远不会改变。不知道是怎么回事,有大侠指点一下吗?

const dataAPI = 'https://restcountries.com/v3.1/'
router.get('/country/:code', (req, res, next) => {
    const code = req.params.code
    fetch(`${dataAPI}/alpha/${code}?fields=borders`)
        .then(response => response.json())
        .then(json => fetch(`${dataAPI}/alpha?codes=${json.borders.join()}&fields=cca3,name`))
        .then(response => response.json())
        .then(bordersJson => {
            fetch(`${dataAPI}/alpha/${code}`)
                .then(response => response.json())
                .then(data => {
                    data.borders = bordersJson
                    res.send(data)
                }).catch(err => next(err))
        }).catch(err => next(err))
})
对于这种情况,

Async/await 是更好的方法。

  const dataAPI = 'https://restcountries.com/v3.1/'
    router.get('/country/:code', async (req, res, next) => {
        try {
            const code = req.params.code;
        const borderJSON = await fetch(`${dataAPI}/alpha/${code}?fields=borders`).then(response => response.json());
        // response:  {"borders":["BGD","BTN","MMR","CHN","NPL","PAK"]}
        const codes = borderJSON.borders.join(',');
        const cca3 = await fetch(`${dataAPI}/alpha?codes=${codes}&fields=cca3,name`)).then(response => response.json());
        //  [{"name":{...},"cca3":"BGD"},{"name":{...},"cca3":"PAK"}]
        res.send(cca3);
        } catch (err) {
            next(err);
        }
    
    });

边框 属性 未被替换的原因是 API 端点使用 returns 一个包含一个对象的数组,而不是对象本身。另外,我发现单独查找边界是不必要的。

最终解决方案

router.get('/country/:code', (req, res, next) => {
    const code = req.params.code
    fetch(`${dataAPI}/alpha/${code}`)
        .then(response => response.json())
        .then(json => {
            json = json[0]
            fetch(`${dataAPI}/alpha?codes=${json.borders.join()}&fields=cca3,name`)
                .then(response => response.json())
                .then(bordersJSON => {
                    json.borders = bordersJSON
                    res.send(json)
                }).catch(err => next(err))
        }).catch(err => next(err))
})