简体   繁体   English

Angular,用settimeout($ q)嘲笑一个诺言

[英]Angular, mocking a promise with settimeout ($q)

I am try ing to set up a test harness for a service, making it take about 1 second to play around with some stuff on the front end. 我正在尝试为服务设置测试工具,使前端大约需要1秒钟才能播放一些东西。

I am using aq so I can call a .then in the controller, so I figuired I could fake this for now by using set timeout, however I think my syntax is incorrect. 我正在使用aq,所以我可以在控制器中调用.then,所以我发疯了,现在可以通过使用set timeout来伪造它,但是我认为我的语法不正确。 Here is what I've tried: 这是我尝试过的:

return $q(function(resolve, reject) {
                        setTimeout(function() {

                        }, 1000).then(resolve);
                    });

I just want it to wait a second then resolve. 我只希望它等待一秒钟然后解决。 New to this, would appreciate any advice, thanks! 对此新手,将不胜感激任何意见,谢谢!

Indeed your syntax is incorrect. 确实,您的语法不正确。 The setTimeout function doesn't return a promise with a .then() method - instead, it takes a callback. setTimeout函数不使用.then()方法返回诺言-而是接受回调。 You'd want to use 您想使用

return $q(function(resolve) {
    setTimeout(function() {
        resolve();
    }, 1000);
});

However, if you use Angular, you should just go for the $timeout service which does return a promise right away. 但是,如果使用Angular,则应该使用$timeout服务 ,该服务会立即返回承诺。

return $q(function(resolve, reject) {
                        setTimeout(resolve, 1000);
                    });

BTW: In angular you should use $timeout service instead of the javascript setTimeout 顺便说一句:在角度,您应该使用$timeout服务而不是javascript setTimeout

Aanyway, in the $q you find also an example with your use case. 无论如何,在$ q中,您还会找到用例的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM