我正在与一个角控制器一起工作,该角色将在上传到服务器的一个或多个调查中添加一个不确定的问题,以相同的名称,这仅是为了理解,上载,后端处理和返回响应无能为力,这里真正的问题是仅上传新问题的特定部分,该问题具有以下功能:
//Will save next question
const next_question = function (response, this_survey, response_survey, sur_questions, question) {
deferred = $q.defer();
new_question = new QuestionsService();
//Does a bunch of stuff with question object using all those arguments,
//which is not relevant here
if (check_existing_question(new_question, sur_questions)) {
deferred.resolve();
}
else {
new_question.$save({
actsern: new_question.actsern
}).then(function () {
deferred.resolve();
}).catch(function () {
deferred.reject();
});
}
return deferred.promise;
};
// Save the questions synchronously (wait for a promise to resolve/reject before saving next question)
async function save_question(response, this_survey, response_survey, sur_questions) {
// I want to store all promises in an array and return for future error handling
promises = [];
for (const quest in response_survey) {
// promise is undefined in console.log!!
promise = await next_question(response, this_survey, response_survey, sur_questions, quest);
console.log(promise);
//Commented because if not returns error "promises.push is not a function"
//promises.push(promise);
}
//Still undefined
console.log(promise);
return promise;
//The above is how I managed to make it work but what I really want is:
//return promises;
}
const set_survey_questions = function(response, this_survey, response_survey){
//Never mind this, unrelated to my problem
let sur_questions = QuestionsService.get({
//this_survey is survey object that is being uploaded to, questions and surveys are linked through actsern
actsern: this_survey.actsern
});
sur_questions.$promise.then(function () {
promises = save_question(response, this_survey, response_survey, sur_questions);
$q.all(promises).then(function () {
console.log("Uploaded successfully all questions");
}).catch(function (reason) {
console.log(reason);
});
});
};
问题是,我必须同步保存问题,等待一个人在保存下一个之前解决/拒绝,这就是为什么我使用异步循环函数的原因。一切正常,问题在订单之后被上传到一个,一切都完全按照预期的方式进入服务器。问题在于,我想从异步功能中获得next_question()
的承诺,以应对其未来的错误,并在使用$q.all()
解决所有其他事情后要做其他事情,但是问题是据我所知await
应该返回诺言,但它只是返回undefined
,即使在循环完成后,也将其保留为undefined
,并且所有诺言都可以解决。
我知道该函数next_question()
工作正常,因为如果直接调用(在异步功能之外,直接从set_survey_questions()
(调用,它将保存问题并按照预期返回承诺。
我对Angular甚至JavaScript的经验不太经验,因此您可以想到的任何帮助或改进。
据我所知,等待的应该返回诺言,但它只是返回未定义的
否。您应该通过 pass 向await
操作员承诺,然后将阻止异步函数的执行,直到承诺解决并返回承诺的结果值 。
问题是我想从异步函数中获得next_question((的承诺,以处理其将来的错误
这似乎与您对顺序节省的要求不兼容。没有多个承诺,一次只有一个活动。如果有任何错误,则await
会抛出异常,而您的循环将停止。
我认为您真的应该简化
async function set_survey_questions(response, this_survey, response_survey) {
let sur_questions = QuestionsService.get({
actsern: this_survey.actsern
});
await sur_questions.$promise;
try {
for (const quest in response_survey) {
await next_question(response, this_survey, response_survey, sur_questions, quest);
}
console.log("Uploaded successfully all questions");
} catch (reason) {
console.log(reason);
}
}