jcalfee314
jcalfee314

Reputation: 4830

Creating own angularjs $q promise

This example is attempting to make synchronous code asynchronous. All examples I found were doing the opposite except the main first example at docs.angularjs.org .. $q below.

The doc lists a $q constructor which I am attempting to use. Unfortunately, the jsfiddle Angular libraries 1.1.1 and 1.2.1 provide a $q object (not a function) as in this example. Instead, I'll have to provide my example and hope that someone will see the bug.

https://docs.angularjs.org/api/ng/service/$q

I need to see "this does not happen!" line to execute.

f = function(name) {
    return $q(function(resolve, reject) {
        console.log "this does not happen!"
        resolve('great')
    });
}


f(name).then(function(result) {
  console.log 'result', result
}, function(error) {
  console.log 'error', error
});

Instead of logging "this does not happen!" followed by "great", I actually see the function passed to $q logged::

    result function(resolve, reject) {
        console.log "this does not happen!"
        resolve('great')
    }

Can someone see what I did wrong?

Upvotes: 4

Views: 3343

Answers (2)

Adam Jenkins
Adam Jenkins

Reputation: 55623

You are doing nothing wrong. I don't really think it's appropriate that the angular docs show that code with this line hidden right above it:

While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are available yet.

It causes much confusion, as you an see.

Use the constructor method (like Zipper posted)

var dfd = $q.defer();

and then you can do the following:

dfd.reject('some value');
dfd.resolve('some value');

Upvotes: 5

Zipper
Zipper

Reputation: 7204

A little hard to see exactly what you're attempting, but here is some code we use that might help.

f = function(someValue){
    var deferred = $q.defer();
    doSomethingAsync(someValue, function(result){ return deferred.resolve(result)});
    return deferred.promise;
}

f("foo").then(function() {alert("I was called after the async thing happened")})

Upvotes: 5

Related Questions