Then () definition after promise is found

I have a question about connecting callback functions to promises in AngularJS.

Suppose I have a service with a function that returns a promise. I make a call to this function and keep the promise locally. Then I define the callback function by promise.

var promise = TestService.get();
console.log('We have a promise!');
promise.then(function (result){
  console.log('Here is the result:'+result);
});

In this case, we have a potentially dangerous situation. If the promise is resolved before we proceed to promise.then(..., the result will not be displayed on the console (until the next digest cycle).

Alternatively, I could write the above code as follows:

TestService.get().then(function (result){
  console.log('Here is the result:'+result);
});

My question is:

? , , , ? , /, :)

+4
3

, , , . factory, , .

'use strict';
var make = function() {
  return new Promise(function(resolve, reject) {
    resolve(2);
  });
};

var prom = make();

, , . , promises , .

prom.then(a => console.log(a));
// 2
prom.then(a => console.log(a));
// 2
+4

, , . . .

, . then, -, . , , .

:

var promise1 = TestService.get();
var promise2 = promise1.then(function(value) {
                  console.log('service resolved: '+value);
                  return "Hello World";
               });
var promise3 = promise2.then(function(value) {
                  console.log(value);
               });
promise3.then(function(value) {
       console.log(value);
});

.

**some value from TestService**
Hello World
undefined

, . , , , . promises, .

. , . (..., ( ).

, , . , , . , . .

, , , , .

? , , , ?

promises . , , , . - , , , . , promises , promises, .

+2

JavaScript is not multithreaded, your asynchronous AJAX call is not actually executed by the browser until your code returns.

var promise = TestService.get();
for (var i= 0;i<100000;i++){
    console.log(i)
}
console.log('We have a promise!');
promise.then(function (result){
    console.log('Here is the result:'+result);
});

Observe this with a network analyzer.

+1
source

Source: https://habr.com/ru/post/1617746/


All Articles