Есть ли способ очистки .then
экземпляра JavaScript Promise
?
Я написал тестовую среду JavaScript поверх QUnit. Структура запускает тесты синхронно, запустив каждый из них в Promise
. (Извините за длину этого кодового блока. Я прокомментировал это как можно лучше, поэтому он чувствует себя менее утомительным.)
/* Promise extension -- used for easily making an async step with a
timeout without the Promise knowing anything about the function
it waiting on */
$$.extend(Promise, {
asyncTimeout: function (timeToLive, errorMessage) {
var error = new Error(errorMessage || "Operation timed out.");
var res, // resolve()
rej, // reject()
t, // timeout instance
rst, // reset timeout function
p, // the promise instance
at; // the returned asyncTimeout instance
function createTimeout(reject, tempTtl) {
return setTimeout(function () {
// triggers a timeout event on the asyncTimeout object so that,
// if we want, we can do stuff outside of a .catch() block
// (may not be needed?)
$$(at).trigger("timeout");
reject(error);
}, tempTtl || timeToLive);
}
p = new Promise(function (resolve, reject) {
if (timeToLive != -1) {
t = createTimeout(reject);
// reset function -- allows a one-time timeout different
// from the one original specified
rst = function (tempTtl) {
clearTimeout(t);
t = createTimeout(reject, tempTtl);
}
} else {
// timeToLive = -1 -- allow this promise to run indefinitely
// used while debugging
t = 0;
rst = function () { return; };
}
res = function () {
clearTimeout(t);
resolve();
};
rej = reject;
});
return at = {
promise: p,
resolve: res,
reject: rej,
reset: rst,
timeout: t
};
}
});
/* framework module members... */
test: function (name, fn, options) {
var mod = this; // local reference to framework module since promises
// run code under the window object
var defaultOptions = {
// default max running time is 5 seconds
timeout: 5000
}
options = $$.extend({}, defaultOptions, options);
// remove timeout when debugging is enabled
options.timeout = mod.debugging ? -1 : options.timeout;
// call to QUnit.test()
test(name, function (assert) {
// tell QUnit this is an async test so it doesn't run other tests
// until done() is called
var done = assert.async();
return new Promise(function (resolve, reject) {
console.log("Beginning: " + name);
var at = Promise.asyncTimeout(options.timeout, "Test timed out.");
$$(at).one("timeout", function () {
// assert.fail() is just an extension I made that literally calls
// assert.ok(false, msg);
assert.fail("Test timed out");
});
// run test function
var result = fn.call(mod, assert, at.reset);
// if the test returns a Promise, resolve it before resolving the test promise
if (result && result.constructor === Promise) {
// catch unhandled errors thrown by the test so future tests will run
result.catch(function (error) {
var msg = "Unhandled error occurred."
if (error) {
msg = error.message + "\n" + error.stack;
}
assert.fail(msg);
}).then(function () {
// resolve the timeout Promise
at.resolve();
resolve();
});
} else {
// if test does not return a Promise, simply clear the timeout
// and resolve our test Promise
at.resolve();
resolve();
}
}).then(function () {
// tell QUnit that the test is over so that it can clean up and start the next test
done();
console.log("Ending: " + name);
});
});
}
Если тест истечет, мой тайм-аут обещания будет assert.fail()
в тесте, чтобы тест был отмечен как неудачный, что все хорошо и хорошо, но тест продолжает работать, потому что тест Promise (result
) все еще ждет его решения.
Мне нужен хороший способ отменить мой тест. Я могу это сделать, создав поле в фрейм-модуле this.cancelTest
или что-то подобное, и проверяя каждую так часто (например, в начале каждой итерации then()
) в тесте, следует ли отменять. Однако в идеале я мог бы использовать $$(at).on("timeout", /* something here */)
, чтобы очистить оставшуюся then()
от моей переменной result
, так что ни один из оставшихся тестов не будет запущен.
Есть ли что-то подобное?
Быстрое обновление
Я попытался использовать Promise.race([result, at.promise])
. Это не сработало.
Обновление 2 + путаница
Чтобы разблокировать меня, я добавил несколько строк с mod.cancelTest
/опросом в тесте. (Я также удалил триггер события.)
return new Promise(function (resolve, reject) {
console.log("Beginning: " + name);
var at = Promise.asyncTimeout(options.timeout, "Test timed out.");
at.promise.catch(function () {
// end the test if it times out
mod.cancelTest = true;
assert.fail("Test timed out");
resolve();
});
// ...
}).then(function () {
// tell QUnit that the test is over so that it can clean up and start the next test
done();
console.log("Ending: " + name);
});
Я установил точку останова в выражении catch
и ударил. Теперь меня смущает то, что оператор then()
не вызывается. Идеи?
Обновление 3
Подумал последнее. fn.call()
выбрасывает ошибку, которую я не поймал, поэтому обещание теста отклонялось до того, как at.promise.catch()
смог его решить.