Javascript $q.when不适用于匿名函数

Javascript $q.when不适用于匿名函数,javascript,angularjs,promise,Javascript,Angularjs,Promise,我正试图将一个同步函数包装成一个承诺 有人能解释一下这两者的区别吗 //没有按预期工作 var promise = $q.promise; promise = $q.when(function() { return 'foo'; }); promise.then(function(result) { console.log('result = ', result); // Prints 'function anonymous()' in chrome console });

我正试图将一个同步函数包装成一个承诺

有人能解释一下这两者的区别吗

//没有按预期工作

var promise = $q.promise;
promise = $q.when(function() {
    return 'foo';
});

promise.then(function(result) {
    console.log('result = ', result); // Prints 'function anonymous()' in chrome console
});
var promise = $q.promise;
promise = $q.when(getIt());

function getIt() {
    return 'foo';
}

promise.then(function(result) {
    console.log('result = ', result); // Prints 'foo' in chrome console
});
//工作如期进行

var promise = $q.promise;
promise = $q.when(function() {
    return 'foo';
});

promise.then(function(result) {
    console.log('result = ', result); // Prints 'function anonymous()' in chrome console
});
var promise = $q.promise;
promise = $q.when(getIt());

function getIt() {
    return 'foo';
}

promise.then(function(result) {
    console.log('result = ', result); // Prints 'foo' in chrome console
});

它返回匿名函数的原因是,您不是在执行函数,您应该在那里编写self-execute函数来调用您的函数

var promise = $q.promise;
promise = $q.when((function() {
    return 'foo';
})());

$q.when不用于执行函数。它旨在包装一个可能是承诺也可能不是承诺的值

设想一个函数获取数据,但有一个缓存,因此如果缓存了该函数,则该值立即返回,否则返回$http承诺。这可能是糟糕的功能设计,但这样的功能确实存在。使用$q.when可以使用相同的简单代码对这两种情况进行操作(不必检查它是承诺还是缓存值)

这对于处理返回奇怪结果的第三方库特别有用

如中所述,您可以避免看起来像

var results = SomeService.getData(); 
if(results && typeof results.then === "function"){
    results.then(doSomething) 
} 
else { 
    doSomething(results) 
};
相反,你可以做一些简单得多的事情,大致如下:

$q.when(SomeService.getData()).then(doSomething);

如果函数的潜在结果(在本例中为
SomeService.getData
)本身就是一个函数,那么自动执行该函数将不是预期的行为,因此
$q。当
不(也不应该)执行您传递的参数时。

@downvoter我可以知道downvote背后的原因吗?回答有什么问题……你是说
$q.when('foo')
?如果您坚持使用该函数,那么一定不要忘记调用它(就像您使用
getIt()