如何实现嵌套的节点提取调用?

时间:2017-11-09 20:39:42

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

例如,我想从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很陌生,并且无法弄清楚如何正确地做到这一点。第一个提取调用工作正常,但嵌套的调用没有那么多。没有错误消息指出我正确的方向。

1 个答案:

答案 0 :(得分:1)

您必须更改此结构:

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

到此:

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

您采用的方式是,您立即调用fetch(),然后将结果传递给.then()。您需要这样做的方式(上面显示的第二个选项)传递一个函数引用,然后可以通过promise基础结构调用LATER。

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

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

在调用.then()处理程序之前,它不执行获取,然后它从fetch()返回新的promise,从而将其链接到原始链中。本答案中第二个代码块中显示的箭头功能示例与最后一个代码块相同。

作为一般性评论,您对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()处理程序中,您有两个结果,可以使用它们来制定您的回复。

相关问题