Javascript Kriskowal Q JS promise 不起作用

标签 javascript jasmine q

我使用 kriskowal/q 模块创建了一个 promise ,但是当我尝试使用它时,它不会进入任何函数,无论是快乐路径还是错误路径。

这是我的 promise 创建类

var Q = require('q');

var Test = function () {

};

Test.prototype = (function () {
    var testt = function () {
        var deferred = Q.defer();
        var x = 5;
        if (x === 5){
            deferred.resolve('resolved');
        }else{
            deferred.error(new Error('error'));
        }
        return deferred.promise;
    };
    return {
        testt : testt
    }
}());

module.exports = Test;

这就是我将如何使用它

var Test = require('../src/js/test.js');

describe("Test", function () {
    "use strict";

    var test = null;

    beforeEach(function () {
        test = new Test();
    });

    it("should return the promise", function () {
        test.testt().then(
            function (a) {
                console.log(a);
            },
            function (b) {
                console.error(b);
            }
        );
    });
});

由于这是一个 Jasmine 测试类,如果您不熟悉 Jasmine ,那么“it”函数内部的内容就是我如何使用 promise 的逻辑。 “testt”是我创建 promise 的函数。为了获得更多说明,我附上了完整的代码。

问题:它不打印 a 或 b

最佳答案

您的it将立即完成,而不是在 promise 解决/拒绝之后完成。

it("should return the promise", function (done) {
    test.testt().then(
        function (a) {
            console.log(a);
            done();
        },
        function (b) {
            console.error(b);
            done();
        }
    );
});

参见here了解更多信息。

关于Javascript Kriskowal Q JS promise 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30478627/

相关文章:

javascript - 在 SVG 世界地图上叠加工具提示样式数据

angularjs - getText() 的返回不能与字符串进行比较

javascript - 如何防止模块的运行 block 在测试期间被执行?

emacs - 在 Emacs 中使用主要模式进入次要模式

javascript - 使用 Q.promises : how to catch an async throw?

javascript - 如何在 mongoDB 中使用 $limit 和 $sort 与 Q.nbind()

javascript - 如何从服务每秒发送 $http.get 请求

Javascript 将多个 <select> 更改为第一个选择的相同选项

javascript - 重置可观察的表单字段 Knockout

javascript - Jasmine 类型错误不是函数