我不太习惯nodejs/javascript中的Promise,基本上我希望我的 Controller 仅在我的promise完成运行后才返回一个值。
我的 Sails 应用程序中有以下服务。我正在使用 request-promise 模块向 facebook graph api 发出 HTTP 请求。
return http(options).then(function(data){
var res = JSON.parse(data);
if(!res || res.error) {
console.log(!res ? 'error occurred while loading photos' : res.error);
return;
}
for (var photoIndex in res.data) {
var photo = res.data[photoIndex];
if (photo.tags) {
for(var tagIndex in photo.tags.data){
var tag = photo.tags.data[tagIndex];
console.log('TAG_ID: '+tag.id + ' -> TARGET_ID: ' + target);
if (tag.id == target) {
photos.push(photo);
}
}
}
}
if (res.paging && res.paging.next) {
console.log('recursion in action!!');
myself(id, target, accessToken, decodeURIComponent(res.paging.next));
}
我的 Controller 是:
var countPhotos = Facebook.countTaggedPhotos(requesterId, targetId, accessToken).then(function(photos){
return res.json({photos: photos.length});
});
但是 Controller 在我的服务 promise 结束之前返回 0,当我查看日志时,我可以看到它仍在执行循环。
如何让我的 Controller 在返回之前等待一切结束,我认为这是 .then()
工作。
最佳答案
当你说这是一个 .then() 工作时,你是对的。当你说
var countPhotos = Facebook.countTaggedPhotos()
您将 countPhotos 设置为等于 countTaggedPhotos().then() 返回的值。在这种情况下,它不会返回照片数量。您可以访问照片数量的唯一位置是 .then 内。
为了进一步帮助您,您需要提供您的相关代码
return http(options).then(function(data){...
因为在那里,您引用了照片,但我不知道它实际上是如何提供给 Controller 中的 .then() 的。
关于javascript - Sails.js Controller 等待异步服务方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29882220/