解析循环中的JavaScript承诺未完成

解析循环中的JavaScript承诺未完成

本文介绍了解析循环中的JavaScript承诺未完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法掌握JavaScript承诺。

I just can't seem to get a hang of JavaScript promises.

在Parse中,我有一个存储Facebook好友ID数组的用户属性。当新用户第一次通过Facebook登录时,我希望迭代使用该应用程序的Facebook好友,然后更新这些用户的Facebook好友阵列以包含这个新用户。

In Parse, I have an attribute on a user that stores an array of Facebook friends IDs. When a new user logs in through Facebook for the first time I want to iterate through their Facebook friends that are using the app, then update those user's Facebook friends array to include this new user.

所以...在用户before_save中我有这个:

So... in user before_save I have this:

var friendsArray = user.get("facebookFriends");
// Iterate through all Facebook friends
_.each(friendsArray, function(facebookId){

   // Retrieve the Facebook friend user
   var query = new Parse.Query(Parse.User);
   query.equalTo("facebookId", facebookId);

   console.log("this executes");
   query.find().then( function(){
       var user = results[0];
       // This does not execute
       console.log("Need to update " + user.get("displayName") + "'s facebook friends");
       return Parse.Promise.as();
   });
}

我的问题与我遇到的另一个问题没有什么不同(),除了这次我需要异步调用的结果才能开始更新用户的Facebook好友阵列。

My problem is not that different than another previous problem I encountered (Parse JavaScript SDK and Promise Chaining), except that this time I need the results of the async call before I can begin updating the user's Facebook friends array.

推荐答案

获取方式这是使用 Parse.Promise.when(),当传递给它的Promise数组得到满足时,它就会被实现。并且循环可以变得更漂亮,如 _。map()

The way to accomplish this is with Parse.Promise.when() which is fulfilled when array of promises passed to it are fulfilled. And the loop can be made prettier as _.map().

var friendsArray = user.get("facebookFriends");
var findQs = _.map(friendsArray, function(facebookId){

    // Retrieve the Facebook friend user
    var query = new Parse.Query(Parse.User);
    query.equalTo("facebookId", facebookId);

    console.log("this executes");
    return query.find();
});

return Parse.Promise.when(findQs).then(function(){
    var user = results[0];
    // This will work now
    console.log("Need to update " + user.get("displayName") + "'s facebook friends");
    return Parse.Promise.as();
});

结果将是一个数组数组 - 因为find返回一个数组 - 通过var- args和下划线_.toArray()在这里很有用,即

The results will be an array of arrays -- since find returns an array --passed as var-args, and underscore _.toArray() is useful here, i.e.

return Parse.Promise.when(finds).then(function() {
    var individualFindResults = _.flatten(_.toArray(arguments));
    // and so on

这篇关于解析循环中的JavaScript承诺未完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:24