是否可以循环解析promise函数?我已经创建了这个方法,但不断收到编译器错误。基本上我想循环遍历数组中的一组值。
Parse.Cloud.define(“getNews”,function(request,response){
var links = [
"xxxxxxx?apikey=xxxxxxxx",
"xxxxxxx?apikey=xxxxxxxx"
];
// var newsJsonData = '{"results": []}';
// var obj;
var count = '';
var promises = _.map(links, function (link) {
return Parse.Cloud.httpRequest({
method: 'GET',
url: "https://www.kimonolabs.com/api/" + link,
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
}).then(function () {
count += test + '\n';
});
});
Parse.Promise.when(promises).then(function(){
response.success(count);
}, function(){
response.error("something went wrong");
});
});
答案 0 :(得分:0)
你非常接近。要实现的是,http请求的resolve函数可以成为收集的promise(即Promise.when()
)的解析函数。
该函数的var arg参数将返回与请求相对应的http响应数组(" a"请求的响应,以及" b"的响应)。
// because it provides lots of useful stuff...
var _ = require('underscore');
Parse.Cloud.define("getNews", function (request, response) {
var count = ["a", "b"];
var promises = _.map(count, function(v) {
return Parse.Cloud.httpRequest({method: 'GET',
url: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
});
});
Parse.Promise.when(promises).then(function () {
var httpResponses = _.toArray(arguments);
var result = _.map(httpResponses, function(httpResponse) {
// For now i'll return string but later will put the data i created
return "string that will someday be a function of httpResponse";
});
return result;
}).then(function (result) {
response.success(result);
}, function (error) {
response.error(error);
});
});
另一种方法,可能更有效,是将一个promise返回解析函数链接到每个单独的http请求。它有点难以阅读,但如果使用http结果执行的操作是另一个异步操作,并且该函数依赖于其他系统资源(与httpRequest不同),那么您可以获得更多并行工作的机器,如此...
var promises = _.map(count, function(v) {
return Parse.Cloud.httpRequest({method: 'GET',
url: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
}).then(function(httpResponse) {
var promise = someNonHttp_PromiseReturningFunction(httpResponse);
return promise;
});
});
Parse.Promise.when(promises).then(function () {
// arguments here will be the resolutions of those
// someNonHttp_... function promises