Create a gist now

Instantly share code, notes, and snippets.

@crguezl /index.html
Last active Mar 14, 2016

What would you like to do?
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<h1> <div id="joke"></div> </h1>
<br/>
<hr />
See <a href="http://www.sitepoint.com/overview-javascript-promises/">An Overview of JavaScript Promises by Sandeep Panda Sandeep Panda</a>.<br/>
<hr />
<p>A <code>Promise</code> object represents a value that may not
be available yet, but will be resolved at some point in future. It
allows you to write asynchronous code in a more synchronous fashion.
<br/>
For example, if you use the Promise API to make an asynchronous
call to a remote web service you will create a <code>Promise</code>
object which represents the data that will be returned by the web
service in future. The caveat being that the actual data is not
available yet. It will become available when the request completes
and a response comes back from the web service. In the meantime the
<code>Promise</code> object acts like a proxy to the actual data.
Further, you can attach callbacks to the <code>Promise</code> object
which will be called once the actual data is available ...</p>
Simply refresh the page to view a new random joke. Also, open up
your browser console so that you can see the order in which the
different parts of the code are executed. Also, note that a
<code>Promise</code> can have three states:</p>
<ul>
<li>pending (not fulfilled or rejected)</li>
<li>fulfilled</li>
<li>rejected</li>
</ul>
<p>The <code>Promise.status</code> property, which is code-inaccessible and private, gives information about these states. Once a Promise is rejected or fulfilled, this status gets permanently associated with it. This means a Promise can succeed or fail only once. If the Promise has already been fulfilled and later you attach a <code>then()</code> to it with two callbacks the success callback will be correctly called. So, in the world of Promises, we are not interested in knowing when the Promise is settled. We are only concerned with the final outcome of the Promise.</p>
</body>
</html>
if(window.Promise) {
console.log('Promise found');
var promise=new Promise(function(resolve,reject){
var request = new XMLHttpRequest();
request.open('GET', 'http://api.icndb.com/jokes/random');
// request.open('GET', 'http://pepe.pum.es/');
request.onload = function() {
if (request.status == 200) {
resolve(request.response); //we get the data here.So, resolve the Promise
}
else {
reject(Error(request.statusText)); //if status is not 200 OK, reject.
}
};
request.onerror = function() {
reject(Error("Error fetching data.")); //error occurred, reject the Promise
};
request.send(); //send the request
});
console.log('Asynchronous request made.');
promise.then(function(data){
console.log('Got data! Promise fulfilled.');
document.getElementById('joke').innerHTML=JSON.parse(data).value.joke;
},function(error){
console.log('Promise rejected.');
console.log(error.message);
});
}
else
console.log('Promise not available');
Owner

crguezl commented Nov 22, 2015

An Overview of JavaScript Promises

Este ejemplo

    index.html
    script.js

está sacado del tutorial:

Estados de una Promise

A promise can be:

  • fulfilled The action relating to the promise succeeded
  • rejected The action relating to the promise failed
  • pending Hasn't fulfilled or rejected yet
  • settled Has fulfilled or rejected

The spec
also uses the term thenable to describe an object that is promise-like, in that it has a then method.

Esquema de una promesa

Here's how you create a promise:

        var promise = new Promise(function(resolve, reject) {
          // do a thing, possibly async, then…

          if (/* everything turned out fine */) {
            resolve("Stuff worked!");
          }
          else {
            reject(Error("It broke"));
          }
        });

The promise constructor takes one argument, a callback with two parameters,
resolve and reject.
Do something within the callback, perhaps async, then call
resolve if everything worked, otherwise call reject.

Usando la Promesa

Here's how you use that promise:

              promise.then(function(result) {
                console.log(result); // "Stuff worked!"
              }, function(err) {
                console.log(err); // Error: "It broke"
              });

then takes two arguments, a callback for a success case, and another for the failure case. Both are optional, so you can add a callback for the success or failure case only.

Véase también

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment