A
A
Alexander Degtyarev2016-05-11 20:34:31
Node.js
Alexander Degtyarev, 2016-05-11 20:34:31

How to understand Promise?

Kind time, help to deal with Promise? I’m studying based on the material of Ilya Kontor - https://learn.javascript.ru/promise and I can’t understand, first a promise instance is created, where the timer is, there are two actions for positive and negative. Next comes the function caller - why, if I can process a promise in an instance, or am I misunderstanding something?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim, 2016-05-11
@ErichAltheim

What is a "function binder"?
You must specify functions on resolve and reject. Since in this way they will have the necessary data in the arguments. And a timer is a good option to "fabricate" an asynchronous action.
The material chosen is good, read it, play around with examples, then look at this article from habr .
Promises need to be felt in practice, and be sure to try to handle errors:
a) when there is no Internet
b) when your api answered not "200"
Then try to execute chains of promises (sequentially, in parallel).
Look in the debugger step by step to see what follows.
Thus, sooner or later it will definitely turn out to be figured out) I, myself, read Cantor after I "poked around" with promise libraries. Therefore, I can’t remember exactly where I started, but his article is good in my opinion.

S
Super User, 2016-05-11
@sergeystepanov1988

Here is a more realistic example, maybe it will be clearer this way:

function fetch(url) {
  return new Promise(function(resolve, reject) {
    $.getJSON(url, function(response) {
      if(response){
        resolve(response); 
      } else {
        reject(new Error('No response'));
      }
    });
  });
}

fetch('http://jsonplaceholder.typicode.com/users').then(function(users){
  var output = '';
  users.forEach(function(user) {
    output += '<p>' + user.name + '</p>';
  });
  $('body').html(output);
}).catch(function(err) {
  console.trace(err.message);
});
JSBIN

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question