gpt4 book ai didi

javascript - 从循环中获取对象解析

转载 作者:行者123 更新时间:2023-12-03 08:35:15 26 4
gpt4 key购买 nike

在解析服务器功能中,它获取匹配项和配置文件。从获取匹配的查询中调用另一个函数来通过 id 获取配置文件,但结果是:

{"_resolved":false,"_rejected":false,"_reso  resolvedCallbacks":[],"_rejectedCallbacks":[]}

主要查询:

mainQuery.find().then(function(matches) {
_.each(matches, function(match) {
// Clear the current users profile, no need to return that over the network, and clean the Profile


if(match.get('uid1') === user.id) {
match.set('profile2', _processProfile(match.get('profile2')))
match.unset('profile1')
}
else if (match.get('uid2') === user.id) {
var profileMatch = _getProfile(match.get('profile1').id);
alert(">>>"+JSON.stringify(profileMatch));

match.set('profile1', _processProfile(match.get('profile1')))
match.unset('profile2')
}

})

获取个人资料信息的函数:

function _getProfile(id){

var promise = new Parse.Promise();



Parse.Cloud.useMasterKey();

var queryProfile = new Parse.Query(Profile);

return queryProfile.equalTo("objectId",id).find()
.then(function(result){

if(result){
promise.resolve(result);
alert("!!!!"+result);
}

else {
console.log("Profile ID: " + id + " was not found");
promise.resolve(null);

}

},
function(error){

promise.reject(error)
});
return promise;
}

最佳答案

发现这个有点晚了。您可能已经继续前进,但对于 future 的读者:解决此类问题的关键是使用 promise 作为小型逻辑异步(或有时异步,如您的情况)操作的返回。

整个 _getProfile 函数可以重述为:

function _getProfile(id){
Parse.Cloud.useMasterKey();
var queryProfile = new Parse.Query(Profile);
return queryProfile.get(id);
}

由于它返回一个 promise ,因此您不能这样调用它:

var myProfileObject = _getProfile("abc123");
// use result here

相反,这样调用它:

_getProfile("abc123").then(function(myProfileObject) { // use result here });

知道了这一点,我们需要重新设计调用该函数的循环。关键思想是,由于循环有时会产生 promise ,因此我们需要让这些 promise 在最后得到解决。

// return a promise to change all of the passed matches' profile attributes
function updateMatchesProfiles(matches) {
// setup mainQuery

mainQuery.find().then(function(matches) {
var promises = _.map(matches, function(match) {
// Clear the current users profile, no need to return that over the network, and clean the Profile

if(match.get('uid1') === user.id) {
match.set('profile2', _processProfile(match.get('profile2'))); // assuming _processProfile is a synchronous function!!
match.unset('profile1');
return match;
} else if (match.get('uid2') === user.id) {
var profileId = match.get('profile1').id;
return _getProfile(profileId).then(function(profileMatch) {
alert(">>>"+JSON.stringify(profileMatch));
match.set('profile1', _processProfile(match.get('profile1')))
match.unset('profile2');
return match;
});
}
});
// return a promise that is fulfilled when all of the loop promises have been
return Parse.Promise.when(promises);
}

关于javascript - 从循环中获取对象解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33233857/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com