.then
JavaScript インスタンスのをクリアする方法はありますかPromise
?
私はJavaScriptのテストフレームワークを書いたQユニットフレームワークは、各テストを で実行することにより、同期的にテストを実行します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 */)
then()
result
このようなものが存在するのでしょうか?
クイックアップデート
を使ってみましたがPromise.race([result, at.promise])
、うまくいきませんでした。
アップデート2 + 混乱
ブロックを解除するために、mod.cancelTest
テストのアイデア内に /polling を含む行をいくつか追加しました。(イベント トリガーも削除しました。)
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()
解決する前にテスト プロミスが拒否されていました。
ベストアンサー1
.then
JavaScript Promise インスタンスの sをクリアする方法はありますか?
いいえ。少なくともECMAScript 6ではそうではありません。Promise(およびそのthen
ハンドラ)はデフォルトではキャンセルできません。(残念ながら)es-discussで少し議論されています(例:ここ) は、これを正しく行う方法について議論しましたが、どのようなアプローチが勝利しても、ES6 には採用されません。
現在の見解は、サブクラス化により、独自の実装を使用してキャンセル可能なPromiseを作成できるようになるというものである。(それがどれだけうまくいくかはわかりません)。
言語委員会が最善の方法を見つけるまで(ES7 ならいいのですが?)キャンセル機能を備えたユーザーランドの Promise 実装を引き続き使用できます。
現在議論されているのはhttps://github.com/domenic/cancelable-promiseそしてhttps://github.com/bergus/promise-cancellation下書き。