[英]Calling Parse.Cloud.httpRequest inside another httpRequest
I'm trying to call an API to retrieve a list of data, this data will help me get image source. 我正在尝试调用API来检索数据列表,这些数据将帮助我获取图像源。 So for each data entry, I try to call the image url and do some image processing using Parse Image.
因此,对于每个数据条目,我尝试调用图像URL并使用Parse Image进行一些图像处理。 The problem is, the inner httpRequest has never been triggered... I don't know what is the reason... As Parse.com is not that popular, I could hardly find any solution for such a case...
问题是,内部的httpRequest从未被触发......我不知道是什么原因......由于Parse.com不是那么受欢迎,我几乎找不到任何解决这种情况的方法......
Here's my code: 这是我的代码:
Parse.Cloud.httpRequest({
url: api_url,
method: 'POST'
}).then(function(data){
data = JSON.parse(data.text);
var entries = data.entries;
for (var i = 0; i < 100; i++) {
entry = entries[i][1];
var image_url = composeImgURL(entry);
Parse.Cloud.httpRequest({
url: image_url,
success: function(httpResponse){
var image = new Image();
image.setData(httpResponse.buffer);
var size = Math.min(image.width(), image.height());
if(size > 300){
var ratio = 300 / size.toFixed(2);
image.scale({
ratio: ratio.toFixed(2)
});
}
image.setFormat("JPEG");
var base64 = image.data().toString("base64");
var cropped = new Parse.File("thumbnail.jpg", { base64: base64 });
cropped.save();
entries[i][1]['url'] = cropped.url;
},
error: function(httpResponse){
console.log(httpResponse);
}
});
}
return entries;
}).then(function(entries){
response.success(entries);
});
Your Current Code Your code will reach the return entries
statement before any of your 100 http requests have completed. 您当前的代码在您的100个http请求完成之前,您的代码将到达
return entries
语句。 As soon as this occurs the line response.success(entries);
一旦发生这种情况,就行
response.success(entries);
will be called, and your cloud function will exit. 将被调用,您的云功能将退出。
Parallel Promises For this situation, what you want to use are parallel promises. 并行承诺对于这种情况,您想要使用的是并行承诺。 The docs are here:
文档在这里:
https://parse.com/docs/js_guide#promises-parallel https://parse.com/docs/js_guide#promises-parallel
There is a relevant question/answer on Parse answers here: https://www.parse.com/questions/parallel-promises-with-parsepromisewhen 这里有关于Parse答案的相关问题/答案: https : //www.parse.com/questions/parallel-promises-with-parsepromisewhen
Future Problems The above will work for simple functionality, however you are doing 2 more things inside your for loop which will require more time 未来的问题上面的内容适用于简单的功能,但是你在for循环中做了两件事,这需要更多的时间
cropped.save();
you should wait for this function to return
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.