有没有一种方法可以清除JavaScript Promise
实例的 .then
方法?
我在QUnit之上编写了一个JavaScript测试框架。该框架通过在Promise
中运行每个测试来同步运行它们。(对于这段代码块的长度,我很抱歉。我尽力进行了注释,所以感觉不那么乏味。)
/* Promise extension -- used for easily making an async step with a
timeout without the Promise knowing anything about the function
it's 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);
});
});
}
如果测试超时,我的超时Promise将在测试上
assert.fail()
,以便将测试标记为失败,这很好,但测试继续运行,因为测试Promise (result
) 仍在等待解决它。我需要一个良好的方法来取消我的测试。我可以通过在框架模块
this.cancelTest
上创建一个字段或类似的东西,并且每隔一段时间(例如在每个then()
迭代的开始)在测试中检查是否要取消来完成它。然而,理想情况下,我可以使用$$(at).on("timeout", /* something here */)
来清除剩余的result
变量上的所有then()
,以便不运行测试的其余部分。有像这样的东西存在吗?
快速更新
我尝试使用
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()
抛出了一个错误,我没有捕获到,因此测试 Promise 在at.promise.catch()
处理之前就被拒绝了。
Prex
库进行Promise取消的回答链接(https://dev59.com/C10a5IYBdhLWcg3whJDW#53093799)添加到文章中。 - noseratio - open to work