【问题标题】:How can I implement nested node-fetch calls?如何实现嵌套的节点获取调用?
【发布时间】:2018-04-22 23:54:02
【问题描述】:

例如,我想从 API(用户)检索一些数据,以便我可以检索更多数据(与该用户关联的团队)。比如:

var fetch = require('node-fetch');

app.get('/users/:username', function (req, res) {   
    var username = req.params.username;
    var user = new Object();
    fetch('https://api.github.com/users/' + username)
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        console.log(json);

        user.handle = json.login;
    }).then(fetch('https://api.github.com/users/' + username + '/repos')
        .then(function(res) {
            return res.json();
        }).then(function(json) {
            console.log(json);
            //user.repos = repos
            var payload = new Object();
            payload.user = user;
            console.log(payload);
            res.send(payload);
        })
    );
});

我对 Node 还很陌生,在弄清楚如何正确执行此操作时遇到了麻烦。第一个 fetch 调用工作正常,但嵌套调用没有那么多。没有错误消息可以为我指明正确的方向。

【问题讨论】:

    标签: node.js fetch-api node-fetch


    【解决方案1】:

    你必须改变这个结构:

    .then(fetch('https://api.github.com/users/' + username + '/repos').then(...))
    

    到这里:

    .then(() => fetch('https://api.github.com/users/' + username + '/repos').then(...))
    

    按照您的操作方式,您立即调用fetch(),然后将其结果传递给.then()。您需要执行此操作的方式(上面显示的第二个选项)传递一个函数引用,该函数引用随后可以由 promise 基础结构调用。

    为了更详细地向您展示实际发生的情况,这是您想要的结构:

    .then(function(priorData) {
        return fetch(...).then(...);
    });
    

    在调用.then() 处理程序之前它不会执行提取,然后它从fetch() 返回新的承诺,从而将其链接到原始链中。此答案中第二个代码块中显示的箭头函数示例与最后一个代码块的实现相同。


    作为一般性评论,您对fetch() 的两次调用不相互依赖,因此您可以同时并行运行它们,这可能会为您带来更快的最终结果。

    一般的方案是:

    Promise.all([fetch(url1), fetch(url2)]).then(function(results) {
        // results[0] is result of first fetch
        // results[1] is result of second fetch
    });
    

    然后,在 .then() 处理程序中,您将获得这两个结果,并且可以使用它们来制定您的响应。

    【讨论】:

    • 我明白你在说什么。我应该阅读这个 Promise 的东西。主要的是,当我的服务器收到获取请求时,我希望在发送包含它们组合数据的响应之前完成两个提取。
    • @VGambit - 然后,您将需要使用我的 Promise.all() 示例(我刚刚修复了一个错误)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多