Skip to content

Instantly share code, notes, and snippets.

@crguezl
Last active November 9, 2020 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crguezl/f5c52c8b72b4722e374a8af10e9d2b5d to your computer and use it in GitHub Desktop.
Save crguezl/f5c52c8b72b4722e374a8af10e9d2b5d to your computer and use it in GitHub Desktop.
Promise simple example
<!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>
// Promises that resolve before the current function ends
// will be executed right after the current function.
//
let promise = new Promise(function(resolve, reject) {
resolve(1)
});
promise.then(function(resolve) { console.log(1) });
console.log('a');
promise.then(function(resolve) { console.log(2); });
setTimeout(function() { console.log('h') }, 0);
promise.then(function(resolve) { console.log(3) });
console.log('b');
/*
* The message queue contains all the events waiting to be executed by the browser (scripts, repaint, reflows/layouts, etc.).
* They are added to the order they are triggered based on event triggering, timers, user input, DOM manipulation, etc.
The event loop pulls from the message queue one at a time and
adds them to the stack for execution.
The job queue is a new queue that contains then() events added to the queue after the completion of a Promise.
In theory the browser can pull from either queue when the event loop occurs.
In practice, Promise jobs are given priority and that queue is emptied first.
This is because the specification specifies then() to be executed after the current event on the call stack is finished.
*/
if(window.Promise) {
console.log('Promise found');
let promise=new Promise(function(resolve,reject){
let request = new XMLHttpRequest();
request.open('GET', 'http://api.icndb.com/jokes/random');
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;
}).catch(
(err) => {
console.log(err);
document.getElementById('joke').innerHTML= err
});
}
else console.log('Promise not available');
#!/usr/bin/env node
'use strict';
process.on('unhandledRejection', error => {
console.log('unhandledRejection:', error.message);
});
let p = new Promise((resolve, reject) => reject(new Error('woops')));
setTimeout(
() => p.catch(error => console.log('caught', error.message)),
1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment