在呈现功能消息时,我需要进行一些API调用以及DB操作。
我有这些长函数,我们称其为 alongFunction
function longFunction(message, item) {
var win = lib.gui.window.get(id);
var msg = message.msg;
var id = message.id;
var direction = message.direction;
//inside are basically some DOM manipulation
//around 10 lines here
//and also there are rendering/misc code
//around 10 lines here
//then we are rendering some messages here:
var msgDiv = $('<div>'), msgTsDiv = $('<div>');
msgDiv.addClass('chat '+direction);
msgDiv.attr('id', id);
if(direction == 'in') {
//I need to add a hook here to do API call, but it takes some time
msgDiv.html('<div class="message in">'+message+'</div>');
} else {
msgDiv.html('<div class="message out">'+message+'</div>');
}
//NEW CODE ADDED HERE: Check below pls
//and because JS is async, it just passes these codes
//around 50 codes for manipulation etc...
if(message.isReceived()) {
msgDiv.addClass('received');
}
//and some other stuff here...
}
我在此处添加了新代码上添加了这些内容:
function longFunction(message, item) {
var win = lib.gui.window.get(id);
var msg = message.msg;
var id = message.id;
var direction = message.direction;
//inside are basically some DOM manipulation
//around 10 lines here
//and also there are rendering/misc code
//around 10 lines here
//then we are rendering some messages here:
var msgDiv = $('<div>'), msgTsDiv = $('<div>');
msgDiv.addClass('chat');
msgDiv.attr('id', id);
//only translating message coming in
if(direction == 'in') {
getTranslatedMessage(message).then(function(newMessage){
//I need to add a hook here to do API call, but it takes some time
msgDiv.html('<div class="message in">'+newMessage+'</div>');
}).catch(function(error){
if(error) {
msgDiv.html('<div class="message">'+message+'<br>'+error+'</div>');
} else {
msgDiv.html('<div class="message in">'+message+'</div>');
}
});
} else {
msgDiv.html('<div class="message out">'+message+'</div>');
}
//end of translation - UPDATE
//and because JS is async, it just pass these codes
//around 50 codes for manipulation etc...
if(message.isReceived()) {
msgDiv.addClass('received');
}
//and some other stuff here...
}
更新: 我尝试过
注意:函数有点长,所以我为此做了一个简单的版本
重要提示:正在循环调用此函数。
提前谢谢!