V
V
vs022017-10-09 03:28:38
Regular Expressions
vs02, 2017-10-09 03:28:38

How are promises different from normal callbacks?

I posted this code here

function someAsyncFunction(num, callback) {
    setTimeout( () => callback(num*2), 1500);
}
function promiseFunction(num) {
    return new Promise((resolve, reject) => {
        setInterval(() => resolve(num*2), 1500)
    });
}

someAsyncFunction(10, res => console.log(res)); // Выведет 20 через 1,5 сек.
promiseFunction(10).then(res => console.log(res)); // Тот же результат

Basically, we do the same thing just in different ways. What is the fundamental difference between these two approaches? after all, the resolve function is essentially the same callback that we use in the first function

Answer the question

In order to leave comments, you need to log in

5 answer(s)
V
Vladimir Kuts, 2019-07-03
@MrChen

^[^#]+$
https://regex101.com/r/QpKjGu/1

S
Sergey delphinpro, 2017-10-09
@vs02

Not the same

function ajax() {
  return fetch(target, fetchOptions)
    .then((response) => {
      if (!target) throw new Error('Invalid url');
      if (response.ok) return response.json();
      throw new Error(`${response.status} ${response.statusText}`);
    })
    .then((json) => {
        if (json['statusOk']) return json;
        throw new Error(json['message'] || 'Server response was not ok');
    });
}

ajax(action, { body: formData })
  .then((json) => {
    console.log('RESPONSE', json);
  })
  .catch((error) => {
    console.error(error);
  });

We can write as many zens as we want, in each one we can do something with the data.
If an error occurs anywhere, it will be handled normally in the catch.
The code is linear, without wild nesting.
With callbacks, you need to track errors at each stage and return them. It is easy to get lost, what came up from where or where it disappeared.
An alternative to error handling is tri/catch. But it doesn't work on asynchronous code.
function myFunc(cb){
  var err = true;
  // имитируем асинхронную операцию
  setTimeout(function(){
    cb(err);
  }, 10);
}

try {
  myFunc(function(err){
    if (err) throw new Error('Oops');
  });
  alert('Всё как бы хорошо!');
} catch(e) {
  alert(e.message);
}

This code will print the message 'Everything seems to be fine!', although everything is bad, there was an error. https://jsfiddle.net/r3zfa4ee/
Promises are different:
function myFunc(){
  let promise = new Promise((resolve, reject) => {
    let err = true;
  
    // имитируем асинхронную операцию
    setTimeout(() => {
      if (err) {
        reject('Ooops!');
      } else {
        resolve(123);
      }
    }, 10);
  });
  
  return promise;
}

myFunc()
  .then(data => {
    alert('Всё точно хорошо!');
  })
  .catch(e => {
    alert(e);
  });

Here the error will be processed properly and we will see the message 'Ooops!' https://jsfiddle.net/43yh8jad/
We can execute promises sequentially. We can execute them in parallel. We can run them for parallel execution, but wait only for the first one to complete (the so-called promise race). Of course, all this can be written without promises, but what will be the difference in the amount of code and in the complexity of its understanding?
And then there's async/await...

K
Konstantin Kitmanov, 2017-10-09
@k12th

Two main differences:
There are no fundamental differences, both approaches are based on how the event loop works in JS and on the fact that the functions there are citizens of the first class. It's just more pleasant to work with promises.

I
Ilya Gerasimov, 2017-10-09
@Omashu

A bunch of all kinds of methods bluebirdjs.com/docs/api-reference.html
And the need to pass errors as the first argument

I
Ivan, 2017-10-09
@LiguidCool

In short, nothing special. It's just "sugar", somewhat simplify the work and understanding of the code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question