【发布时间】:2017-02-27 08:31:53
【问题描述】:
我正在编写一个程序,它接受一个句子并用数据库中的完整术语替换缩写词(例如,“hi and gm”->“hello and good morning”,如果存储在数据库中的缩写词是“hi”- ->“你好”和“gm”->“早上好”)。原句存储在$('#translation').text()中,应相应替换。
所以我发现了如何使用 Promise 让 getFullSentence() 等到 for 循环完成每个单词的辅助函数 getFullWord()。
问题是 getFullWord() 没有按顺序执行,例如如果我记录“i”,我会得到 0、3、1、2 而不是 0、1、2、3。我该如何解决这个问题?提前谢谢!
function getFullSentence(uid, sentence) {
var promises = [];
var words = sentence.split(" ");
$.each(words, function(i, word) {
promises.push(getFullWord(uid, word, i));
});
$.when.apply(null, promises).done(function() {
play($('#translation').text());
});
}
function getFullWord(uid, word, i) {
var defer = $.Deferred();
$.get("/checkAbbreviation/" + uid + "/" + word, function(data) {
word = data.full;
var currSentence = $('#translation').text() + " ";
var newSentence = currSentence + word.toUpperCase();
$('#translation').text(newSentence);
}).done(function() {
defer.resolve();
});
return defer.promise();
}
【问题讨论】:
-
$.Deferred()在getFullWord()函数中不是必需的,.done()返回一个 jQuery 承诺对象。i不用于getFullWord。您可以在问题中包含play的文本吗?为什么getFullSentence没有返回值?使用链接到$.get()的.then()而不是$.get()回调和.done() -
感谢您的回复! play() 调用一个名为 ResponsiveVoice.js 的库来说出句子。 getFullSentence() 不需要返回任何东西,因为它只是调用了 play() 函数
标签: javascript jquery get promise deferred