How does Angular $q.when work?

70,735

Calling $q.when takes a promise or any other type, if it is not a promise then it will wrap it in a promise and call resolve. If you pass a value to it then it is never going to be rejected.

From the docs:

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

Share:
70,735
SET001
Author by

SET001

Main area of interests: Node.js, TypeScript, React/Redux/Rx.js As a hobby - HTML5 GameDev, Rust/Rust GameDev [email protected]

Updated on December 04, 2020

Comments

  • SET001
    SET001 over 3 years

    Can some one explain me how does $q.when work in AngularJS? I'm trying to analyse how $http work and found this:

    var promise = $q.when(config);
    

    And here is config object from Chrome console:

    Object {transformRequest: Array[1], transformResponse: Array[1], cache: Object, method: "GET", url: "/schedule/month_index.html"…}
    cache: Object
    headers: Object
    method: "GET"
    transformRequest: Array[1]
    transformResponse: Array[1]
    url: "/schedule/month_index.html"
    __proto__: Object
    

    What happens next? How this object get's resolved or rejected?

  • SET001
    SET001 about 11 years
    If you pass a value to it - but what if I passing object?
  • Phrygian Moon
    Phrygian Moon about 11 years
    value, object, array it is all the same.
  • Onur Topal
    Onur Topal over 9 years
    what if I pass a function that returns a promise? does it mean the then callback of it will be passed the promise result param send by resolve?
  • jrista
    jrista over 9 years
    Onur, when you say pass a function, do you mean as a function object: $q.when(myfunc), or by invoking the function your passing in: $q.when(myfunc())? I don't know exactly what the former will do...the latter will invoke myfunc() first, and pass the returned promise|value to .when().