我有这个功能:
waitForFreeAccnt.prototype.isMemberFree = function () {
var self = this;
self.api.getMemberInfo(function () {
var accType = self.api.connect.accountType;
console.log(accType);
if (accType === 'FREE') {
console.log('it is free');
return true;
} else {
console.log('it is not free');
return false;
}
});
};
我想等到帐户空闲最多 10 秒,然后执行类似的操作:
var test = function () {
for (var start = 1; start < 10; start++) {
var result = self.isMemberFree();
console.log(result);
if (result) {
break;
} else {
self.api.pause(1000);
console.log('waiting');
}
}
};
但它不起作用,因为 self.api.getMemberInfo
是异步调用。这对 Javascript 来说非常令人沮丧。任何其他语言都会如此简单。如何强制 for 循环等待 self.isMemberFree()
在继续循环之前完成执行?
还要注意,这不是在浏览器执行中,所以我不关心任何挂起的东西。
最佳答案
在处理异步代码时,您需要使用回调。也就是说,如果你想按顺序执行 a()
和 b()
但 a()
异步执行某些操作,那么你需要一旦 a()
有结果,就从 a()
中调用 b()
。所以不是:
a(); // does something asynchronously
b(); // tries to use a()'s result but it isn't available yet
...而是
a(b); // pass b to a() and a() will call it when ready
function a(callback) {
triggerAsyncFunction(function(result) {
if (result === something)
callback("a just finished");
});
}
请注意,a()
并未按名称引用 b()
,它只是调用作为参数传入的任何函数。
所以将它应用到您的代码中,可能是这样的:
waitForFreeAccnt.prototype.isMemberFree = function (cbf) {
var self = this;
self.api.getMemberInfo(function () {
cbf(self.api.connect.accountType === 'FREE');
});
};
waitForFreeAccnt.prototype.testMemberXTimes = function(maxAttempts, callback) {
var attempts = 0;
var self = this;
(function attempt() {
self.isMemberFree(function(free) {
if (free)
callback(true);
else if (++attempts < maxAttempts)
setTimeout(attempt, 1000);
else
callback(false);
});
)();
};
this.testMemberXTimes(10, function(isFree) {
// the next part of your code here, or called from here
// because at this point we know we've tested up to
// ten times and isFree tells us the result
});
请注意,我编写 getMemberInfo()
的方式基本上与您的方式相同,但不是返回 bool 值,而是调用回调函数并传递与您相同的 bool 值返回。 (我删除了 console.log()
以使代码更短。)
另请注意,您可以构建上述内容以使用 promise ,但最终结果将是相同的。
关于javascript - 如何在 Javascript 中执行具有异步条件的 "for"循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37902092/