简体   繁体   中英

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.

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. 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. 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.

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

BTW: In angular you should use $timeout service instead of the javascript setTimeout

Aanyway, in the $q you find also an example with your use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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