4

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?

2 Answers 2

5

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');
Sign up to request clarification or add additional context in comments.

Comments

5

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")})

1 Comment

I don't have a luxury of having a doSomethingAsync method with a call back. Looks like it can not be done with the typical $q.defer() method. One example is to wrap file IO the mimics the localstorage in the browser. The nodejs side will use a file synchronous side to mimic the real standard. That is synchronous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.