<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test-pre.js"></script>
</head>
<body>
<div id="description"></div>
<div id="console"></div>
<script>
description('Test Promise.');

window.jsTestIsAsync = true;

var resolve;
var promise = new Promise(function (r) {resolve = r;});
var operation;

promise.then(function(result) {  // fulfilled - continue
  testPassed('fulfilled');
  window.result = result;
  shouldBeEqualToString('result', 'hello');
  return 'hello2';
}, function() {
  testFailed('rrejected');
}).then()  // pass through
.then(function(result) {  // fulfilled - throw an exception
  testPassed('fulfilled');
  window.result = result;
  shouldBeEqualToString('result', 'hello2');
  throw 'error';
}, function() {
  testFailed('rejected');
}).then(function() {  // rejected - throw an exception
  testFailed('fulfilled');
}, function(result) {
  testPassed('rejected');
  window.result = result;
  shouldBeEqualToString('result', 'error');
  throw 'error2';
}).then() // pass through
.then(function() {  // rejected - recover
  testFailed('fulfilled');
}, function(result) {
  testPassed('rejected');
  window.result = result;
  shouldBeEqualToString('result', 'error2');
  return 'recovered';
}).then(function(result) {  // fulfilled - the last
  testPassed('fulfilled');
  window.result = result;
  shouldBeEqualToString('result', 'recovered');
  shouldBeEqualToString('operation', 'asynchronous');
  finishJSTest();
}, function() {
  testFailed('rejected');
  finishJSTest();
});

operation = 'synchronous';
resolve('hello');

// The chain should be executed asynchronously.
operation = 'asynchronous';

</script>
<script src="../../resources/js-test-post.js"></script>
</body>
</html>
