Time boxed Promise

by Arnaud Buchholz

JavaScript

function getTimeBoxedPromise (nMaxTimeout) {
  return new Promise(function (resolve, reject) {
    var timerId = setTimeout(function () {
      reject(new Error("timeout"));
    }, nMaxTimeout);
    setTimeout(function () {
      resolve();
      clearTimeout(timerId);
    }, 100);
  });
}

// First will succeed
getTimeBoxedPromise(150)
	.then(function () {
    alert("OK");
  }, function (reason) {
    alert("KO: " + reason);
  })
	// Second will fail
  .then(function () {
  	return getTimeBoxedPromise(50);
  })
  .then(function () {
    alert("OK");
  }, function (reason) {
    alert("KO: " + reason);
  });