gpt4 book ai didi

javascript - 如何在 node.js 中异步递归 API 回调?

转载 作者:数据小太阳 更新时间:2023-10-29 04:03:43 25 4
gpt4 key购买 nike

API 调用返回结果的下“页面”。如何优雅地递归该结果回调?

这是我需要执行此操作的示例:

var url = 'https://graph.facebook.com/me/?fields=posts&since=' + moment(postFromDate).format('YYYY-MM-DD') + '&access_token=' + User.accessToken;
request.get({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
_.each(body.posts.data, function (post) {
User.posts.push(post); //push some result
});
if (body.pagination.next) { // if set, this is the next URL to query
//?????????
}
} else {
console.log(error);
throw error;
}

});

最佳答案

我建议将调用包装在一个函数中,并在必要时继续调用它。

我还会添加一个回调以了解流程何时完成。

function getFacebookData(url, callback) {

request.get({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
_.each(body.posts.data, function (post) {
User.posts.push(post); //push some result
});
if (body.pagination.next) { // if set, this is the next URL to query
getFacebookData(body.pagination.next, callback);
} else {
callback(); //Call when we are finished
}
} else {
console.log(error);
throw error;
}

});
}

var url = 'https://graph.facebook.com/me/?fields=posts&since=' +
moment(postFromDate).format('YYYY-MM-DD') + '&access_token=' + User.accessToken;

getFacebookData(url, function () {
console.log('We are done');
});

关于javascript - 如何在 node.js 中异步递归 API 回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17242600/

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