有没有清除.thenJavaScript Promise实例的方法?
我在QUnit上编写了一个JavaScript测试框架.框架通过在a中运行每个框架来同步运行测试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 …Run Code Online (Sandbox Code Playgroud) async function update() {
var urls = await getCdnUrls();
var metadata = await fetchMetaData(urls);
var content = await fetchContent(metadata);
await render(content);
return;
}
//All the four functions return a promise. (getCdnUrls, fetchMetaData, fetchContent, render)
Run Code Online (Sandbox Code Playgroud)
如果我们想在任何时间从外部中止序列怎么办?
比如,当执行fetchMetaData时,我们意识到不再需要渲染组件,我们想要取消剩余的操作(fetchContent和render).消费者有没有办法从外面中止/取消?
我们可以在每次等待一个条件后检查,但这似乎是一种不太优雅的方式.它仍然会等待当前的操作完成.