1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
| 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.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');
|
Promises that resolve before the current function ends will be executed right after the current function.
1
| [~/.../p2-t1-c3-file-system/event-loop/promise-ejemplo/(master)]$ cat promise-job-queue.js
|
1
| [~/.../uai2015/promise-ejemplo(master)]$ pwd -P
|
1
2
3
4
5
6
7
8
9
10
11
12
| #!/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);
|
1
2
3
4
| [~/.../uai2015/promise-ejemplo(master)]$ ./unhandled-promise-rejection.js
unhandledRejection: woops
caught woops
(node:25246) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
|