javascript - Promises 和 Deferred : . did() 和 .then() 被调用,尽管 .resolve() 在 Deferred 对象上被调用

标签 javascript jquery html promise jquery-deferred

我是 Javascript 和 JQuery 新手。根据我的理解, .then() 和 .done() 是由于延迟对象上的resolve()而被触发的。但在我的代码中,虽然没有调用resolve(),但.then()和.done()被触发

<head>
    <meta charset="UTF-8">
    <title>Testing Promises</title>
</head>

<body>

<button type="button" onclick="test()"> Click Me</button>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>

    function test() {
        var promise = $.when(another);
        promise.done(function () {
            console.log("another() done");
        });

        promise.done(function () {
            console.log("another() done 2");
        });

        promise.done(function () {
            console.log("another() done 3");
        });

        promise.fail(function (error) {
            console.log("Failed with error = ", error);
        });

        promise.then(function () {
            console.log("In then():");
        });

        console.log("test() done");
    }


    function another() {
        var def = $.Deferred();

        console.log("In another()");
        return def.promise();
    }
</script>

</body>

</html>

最佳答案

$.when(another)another 函数的(立即履行的) promise 。您会想要使用

var promise = $.when(another());

或者只是

var promise = another();

实际调用该函数并创建从未解析的def

关于javascript - Promises 和 Deferred : . did() 和 .then() 被调用,尽管 .resolve() 在 Deferred 对象上被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38469903/

相关文章:

javascript - 删除本地存储中的字符串

javascript - 创建数组的 javascript 对象字面量

javascript - 使用 javascript 内联表单标签和字段

javascript - 我的 jQuery 插件参数无法正确触发时遇到问题

javascript - 我可以创建一个指向当前页面的 html 链接而不刷新到顶部吗?

javascript - 显示上传的图片而不是上传按钮

javascript - 简单模式自动注销

javascript - Angular + jQuery,当图片src改变时触发滚动

android - 样式属性在 webview 中不起作用

javascript - 更改 id 以填充 html 表