javascript - 延迟语句(例如promise() 和done())如何工作?

标签 javascript jquery

我需要帮助理解诸如 promise()done() 之类的延迟方法的使用。

1st) 在这个例子中,.promise()被添加到animate中,其中done()被调用。

        var stack = new Array();

        $(document).ready(function() {
            $(".droppable").each(function(){
                stack.push(new Droppable($(this)));  
            });
            dropNext();
        });

        function dropNext(){
            var droppable = stack.pop();
            if(droppable){                  
                droppable.drop().done(dropNext);
            }
        }

        function Droppable(domElem) {

            function drop() {
                return domElem.animate(
                    {
                        opacity : "1"
                    }
                ).promise(); 
            }
            this.drop = drop;
        }

这个 promise 的目的是什么?它是如何工作的?

第二)jQuery 文档给出 this sort of example与 $.get,但不知道它与使用已随 $.get() 提供的匿名函数回调有何不同:

   $.get("test.php", {},
        function (result) { 
            alert(result);
        }
     );


    $.get( "test.php" ).done(
        function(result) {
            alert(result);
        }
    );

匿名函数不是已经是一个回调,用于返回从服务器返回时要解析的结果吗?

最佳答案

promise 是一种跟踪延迟结果的方法,使异步操作看起来像同步操作。在您给出的示例中,链中只有一个链接,回调也同样有效。真正的力量在于多个链接,并允许错误上升到顶层进行处理。

对于您的第一个示例,animate 需要一些时间,因此返回一个在动画完成时解析的 promise 可以让您确保上一个动画在之前完成下一篇开始。它表示“我正在告诉您现在要做什么,但在其他事情完成之前不要这样做。”如果您的列表堆叠 这里有 5 个元素,你可以循环遍历并将它们与上面的代码链接在一起。要使用回调来完成此操作,您需要将回调嵌套 5 层深。

promise 的核心是then,允许将多个操作链接在一起。查看 $.get 示例,假设您想要执行多个相互依赖的 API 调用:

$.get("test.php", {},
    function (result) { 
        $.post("test-details.php", {data: result}, function(detail) {
            $.get("test-content.php", {id: detail.id}, function(content) {
                // do content stuff
                // whoa, this is getting deep
            });
        });
    }
 );

您可以使用 Promise 来解决这个问题。

$.get( "test.php" ).then(function(result) {
    return $.post("test-details.php", {data: result});
}).then(function(detail) {
    return $.get("test-content.php", {id: detail.id});
}).then(function(content) {
   // do content stuff
});

您可以通过将其转到链的末尾来捕获沿途发生的任何错误。

要进一步阅读,我推荐You're missing the point of promises和[ promise Anit-https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns )(来自 bluebird 。)

关于javascript - 延迟语句(例如promise() 和done())如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27302589/

相关文章:

javascript - UIWebView iOS document.getElementByID 不起作用

javascript - Angular 2 : Two backend service calls on success of first service

javascript - li作为使用 Vanilla Javascript的选择项

javascript - 使用JavaScript根据输入值更改innerText的颜色

javascript - 更改输入框也需要在JS中查找是否选中复选框

jquery - DIV 的动态 anchor 标记,但 CSS 点击不起作用

javascript - 在 Bootstrap 导航栏中时,下拉菜单溢出不起作用

javascript - VueJs 仅将数组插入数组值

javascript - 如何让 bootstrap-datetimepicker 以 15 分钟为间隔显示时间

javascript - 如何聚焦隐藏的输入字段