本文介绍了AngularJS和Q.fcall的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angulars $ Q 是一个承诺/延期执行由克里斯·科瓦尔Q值的启发。

Angulars $q is a promise/deferred implementation inspired by Kris Kowal's Q.

在Q,你创建一个承诺

var myPromise = Q.fcall(myFunction);

下面的 myFunction的将被异步调用,一个承诺被放置在 myPromise 变量和$ C $ ç继续执行。

Here the myFunction will be invoked asynchronously, a promise is placed in the myPromise variable and the code execution continues.

href=\"http://docs.angularjs.org/api/ng/service/%24q\" rel=\"nofollow\">唯一的例子角的暂停的功能,这对我来说似乎是比上述Q例如一个详细的黑客。因此,在角我会写

The only example Angular gives for creating a promise is using javascript timeout function, which to me seems like a verbose hack compared to the above Q example. So in Angular I would write

function asyncWorker(name) {
  var deferred = $q.defer();

  setTimeout(function() {
    scope.$apply(function() {
      deferred.resolve(myFunction);
    });
  }, 1000);

  return deferred.promise;
}

以上是相同的顶部的一行代码。

The above would be identical to the one-liner at the top.

我希望 $ q.fcall 会的工作,但我得到:

I hoped that $q.fcall would have worked but I get:

TypeError: 'undefined' is not a function (evaluating '$q.fcall(function() { return 'a'; })')

那么什么是异步调用的函数,并返回在AngularJS承诺最直接的方法是什么?

So what's the most straightforward way of asynchronously invoking a function and returning a promise in AngularJS?

推荐答案

好吧,更清洁的替代被注入角的 $超时,让我们再一次说,函数 myFunction的是我想asynchroniously做的工作,我只是做:

Ok, cleaner alternative is injecting Angular's $timeout and let's say again that function myFunction is the work I want to do asynchroniously, I'll just do:

function doWorkAsync() {
   return $timeout(myFunction, 10);
}

doWorkAsync 将返回当 myFunction的已完成了它的工作。将要解决的承诺

and doWorkAsync will return a promise that will be resolved when myFunction has finished it's work.

有关的单元测试,我可以叫 $ timeout.flush()立即触发超时功能。

For unit testing I can call $timeout.flush() to fire the timeout function instantly.

这篇关于AngularJS和Q.fcall的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 07:54