K
K
Kirill Tekord2017-06-21 01:20:42
JavaScript
Kirill Tekord, 2017-06-21 01:20:42

When exactly is a promise triggered and can it (theoretically) execute faster than .then is called?

In the subject of the question is its essence. I am not a strong JavaScript expert, I study promises, I read in the documentation that the promise code starts executing immediately after the creation of the promise object. But we make calls to .then and .error AFTER the Promise object is created. Example:

fetchResult(query) // возвращает промис
    .then(function(result) {
        return processResult(result);
    })
    .then(function(processedResult) {
        console.log('processed result', processedResult);
    });

QUESTION: Can it happen that a promise is executed faster than .then is called?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey delphinpro, 2017-06-21
@tekord

Promise can be completed faster. It's right.
But then will also be executed.
You can see for yourself by running the code

var promise = new Promise(function(resolve, reject) {
  console.log('I\'m promise');
  resolve('resolve');
});

for (var i=0; i<10000; i++) {
  console.log(1);
}

promise.then( function (result) {
  console.log(result);
  return 'f1';
});

promise.then( function (result) {
  console.log(result);
  return 'f2';
});

Console output
I'm promise
(10000 раз) 1
resolve
resolve

S
Stalker_RED, 2017-06-21
@Stalker_RED

First, the query will be executed, then, if there were no errors, the first then, then, if there were no errors, the second. For the sake of observing this sequence, as it were, everything was conceived.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question