如何使用promise返回从递归AJAX调用构建的集合
How to use promises to return a collection built from a recursive AJAX call?
我正在从soundcloud API请求数据。它提供每个请求200个跟踪的json结果,以及一个名为"next_href"的字段,该字段基本上是API对下200个结果的调用(或剩余的许多结果)。这就是为什么我必须制作一个递归函数。目前,我能够获得完整的集合,并在递归结束时解析promise。但是,我不确定如何将集合返回到主函数。在我重新构造这个函数以使用promise之前,我只是在递归的最后回调中调用addTracks,这很有效,但我想抽象这个函数,以便它可以用于任何soundcloud API调用。
以下是我目前所拥有的:
function main(){
// Use the user's soundcloud ID to request the their likes
var url = "https://api-v2.soundcloud.com/users/" + userid + "/likes?offset=0&limit=200";
var promise = getCollection(url);
promise.then(function(collection){
console.log("got here");
//would like to have the collection to use here
//addTracks(req, res, collection, 0);
})
}
function getCollection(url){
var deferred = Q.defer();
recurse(url, [], deferred);
return deferred.promise;
}
function recurse(url, collection, promise){
console.log(url);
requestify.get(url).then(function(response){
collection = collection.concat(response.getBody().collection);
console.log(collection.length);
if (response.getBody().next_href != null){
var newurl = response.getBody().next_href;
recurse(newurl, collection, promise);
}
else {
promise.resolve();
}
})
}
您不需要使用延迟。相反,只需返回下一步的承诺:
function main(){
// Use the user's soundcloud ID to request the their likes
var url = "https://api-v2.soundcloud.com/users/" + userid + "/likes?offset=0&limit=200";
var promise = getCollection(url);
promise.then(function(collection){
console.log("got here");
//would like to have the collection to use here
addTracks(req, res, collection, 0);
});
}
function getCollection(url){
return recurse(url, []);
}
function recurse(url, collection){
console.log(url);
return requestify.get(url).then(function(response){
collection = collection.concat(response.getBody().collection);
console.log(collection.length);
if (response.getBody().next_href != null){
var newurl = response.getBody().next_href;
// Wait for the next call to complete and return its result.
return recurse(newurl, collection);
} else {
// This is the final result of the promise
return collection;
}
})
}
相关文章:
- 构建Ajax调用数组时,JQueryAjax成功回调不起作用
- 通过服务器调用Graph API来构建我自己的Facebook帖子数据库
- 在Jenkins作业配置页面中,当我的自定义构建步骤添加到作业配置页面时,如何调用JavaScript函数
- 从 ajax 调用到 jquery UI 可排序列表构建 html
- 如何重新构建此 for 循环,以便在异步 api 调用完成之前不会进行下一次迭代
- 电话差距构建地理位置 NPObject 上的错误调用方法
- Requirejs:dist 失败,加载器插件没有在构建:文本中调用加载回调
- 尝试调用 place 并在已经构建的 html 页面中运行 javascript 函数
- 如何在 javascript 中干净地构建多个异步调用
- JQuery Ajax调用在构建后在Phonegap中不起作用
- 如何构建 json 跨域调用 php
- 对一个's的成功构建依赖于Nodejs中的http调用
- 如何使用promise返回从递归AJAX调用构建的集合
- 使用AJAX/Javascript/jQuery构建和调用多维数组
- 如何使用asp.net mvc和knockoutjs构建对javascript函数的动态调用
- 如何通过多次调用在Angular JS服务或控制器中构建模型数据
- 在由EmberCLI构建的EmberJS中,如何调用不同控制器上的方法
- Ajax没有在framework7的构建版本中调用API
- 用调用RSS提要的脚本动态构建iframe
- 如何用api调用来构建React App的所有登录、注册和主页