【发布时间】:2019-12-26 08:18:05
【问题描述】:
我在后台的代码中使用了一个繁重的第 3 方 JavaScript 库。我对 1 个功能的问题是,它可能需要一段时间才能使用,并且用户可以在此之前使用该功能。
第二个问题是利用可能不可用的客户端安装功能。在第一种情况下,启动操作异步是没有问题的,但需要有一个超时,之后它会失败,以防客户端安装丢失并且该功能永远不可用(有一个功能可以检查该功能是否已启用)。
(我也不熟悉新的 ES 特性,比如 promise 和 async await)
我怎样才能做到这一点?
编辑:
客户端安装:需要从组件中复制二进制数据的这一功能。 (它还需要一个 chrome 扩展)。
EDIT2:
//on button click
if (container === undefined || !container.canPerfromAction()) {
//wait till condition is wrong up to timeout value (2 seconds for example). This is what doesn't work. Simple sleep would be needed but doesn't seem to exist in JS
}
//check again and fail if not available works fine
container.performAction(); //involves ajax call
然后再次检查,如果条件仍然失败(超时命中),用户将看到带有相应信息的错误对话框。除了等待部分之外,这有效。
编辑3:
答案/解决方案
既然问题在这里被spergs阻止了,我的问题的答案(为什么spergs从来没有真正提供有用的答案?)
解决方案来自here
// The polling function
function poll(fn, timeout, interval) {
var endTime = Number(new Date()) + (timeout || 2000);
interval = interval || 100;
var checkCondition = function(resolve, reject) {
// If the condition is met, we're done!
var result = fn();
if(result) {
resolve(result);
}
// If the condition isn't met but the timeout hasn't elapsed, go again
else if (Number(new Date()) < endTime) {
setTimeout(checkCondition, interval, resolve, reject);
}
// Didn't match and too much time, reject!
else {
reject(new Error('timed out for ' + fn + ': ' + arguments));
}
};
return new Promise(checkCondition);
}
// Usage: ensure component is available
poll(function() {
return container != undefined && container.canPerfromAction());
}, 2000, 150).then(function() {
container.performAction();
}).catch(function() {
// Polling timed out
$( "#error" ).dialog( "open" );
});
【问题讨论】:
-
你能详细解释一下你在说什么类型的库吗?我不明白为什么有必要执行任何“客户端安装”,这应该如何工作以及这意味着什么?
-
a user could make use of the feature before that- 如果您正确编写代码,他们就不能 -
您应该熟悉异步加载等。Google 先生将通过在 javascript 中搜索“延迟加载”、“异步加载”、“动态加载”等术语来提供帮助。
-
在这里理解 Promise 是一个简单的例子 let promiseToDoTheWork = new Promise(function(resolve, reject){ // 在这里调用你的第 3 方函数 if (isOK) { //resolve("好吧! "); } else { reject("发生错误"); } }); promiseToDoTheWork .then(function(message){ console.log("结果:" + message ); }) .catch(function(message){ console.log("不幸的是:" + message ); });您必须提供一些代码让我们了解您的实际问题。
-
@JaromandaX 不正是我要问的吗?在这里,解决方案实际上会有所帮助,而不是明智的评论。
标签: javascript asynchronous timeout