Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 933
jcalfee314 Avatar asked Dec 25 '22 01:12

jcalfee314


2 Answers

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');
like image 58
Adam Avatar answered Dec 28 '22 07:12

Adam


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")})
like image 31
Zipper Avatar answered Dec 28 '22 05:12

Zipper