将脚本的一部分转换为带承诺的回调

时间:2019-02-17 05:38:29

标签: javascript asynchronous callback

在呈现功能消息时,我需要进行一些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...
}

更新: 我尝试过

  • 将所有内容放入一个大的回调=中,但不会返回任何结果。
  • 通过将其余代码复制粘贴到回调中并在外部重复=印出的消息的顺序不正确(此函数在循环中被调用)

注意:函数有点长,所以我为此做了一个简单的版本

重要提示:正在循环调用此函数。

提前谢谢!

0 个答案:

没有答案