- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
{ for await(let t of asynDataStreamOrGenerator-6ren">
如果异步循环没有在预期的时间段内完成,是否有打破异步循环的技术?
我有这样的代码:
(async()=>{
for await(let t of asynDataStreamOrGenerator){
//some data processing
}
//some other code I need to run based on whatever data collected by
//asyncDataStreamOrGenerators within given time period
})()
如果此循环未在某个时间跨度内完成,则跳出循环并进一步处理请求。
最佳答案
(另见 community wiki answer I posted 的另一种方法。)
在评论中你说:
I am designing a consensus algorithm, where every source needs to send the response within a given time frame. If some of such participants are dead!, I mean they do not send values, the loop will be held for ever!
Promise.race
带有一个围绕计时器机制的 promise (
setTimeout
或类似的)。
Promise.race
观察你传递给它的 promise ,并在它们中的任何一个完成后立即完成(传递该履行或拒绝),而不管其他人后来如何解决。
for-await-of
并直接而不是间接地使用结果对象的 promise 。假设你有一个效用函数:
const delay = (ms, value) => new Promise(resolve => {
setTimeout(resolve, ms, value);
});
这将返回一个 promise ,它会在 X 毫秒后使用您提供的任何值(如果有)来履行。
(async () => {
const TIMEOUT = 500; // Milliseconds
const GOT_TIMEOUT = {};
const it = asynDataStreamOrGenerator[Symbol.asyncIterator]();
try {
while (true) {
const p = it.next();
const result = await Promise.race([p, delay(TIMEOUT, GOT_TIMEOUT)]);
if (result === GOT_TIMEOUT) {
// Didn't get a response in time
console.log("Timeout");
} else {
// Got a response
if (result.done) {
// Iteration complete
console.log("Iteration complete");
break;
}
// ...some data processing on `result.value`...
console.log(`Process ${result.value}`);
}
}
} finally {
try {
it.return?.(); // Close the iterator if it needs closing
} catch { }
}
})();
使用随机持续时间进行异步迭代器工作的实时示例,但在第三次迭代时强制超时:
const delay = (ms, value) => new Promise(resolve => {
setTimeout(resolve, ms, value);
});
async function* example() {
for (let i = 1; i <= 6; ++i) {
const ms = i === 3 ? 600 : Math.floor(Math.random() * 100);
await delay(ms);
yield i;
}
}
(async () => {
const asynDataStreamOrGenerator = example();
const TIMEOUT = 500; // Milliseconds
const GOT_TIMEOUT = {};
const it = asynDataStreamOrGenerator[Symbol.asyncIterator]();
try {
while (true) {
const p = it.next();
const start = Date.now();
const result = await Promise.race([p, delay(TIMEOUT, GOT_TIMEOUT)]);
const elapsed = Date.now() - start;
if (result === GOT_TIMEOUT) {
// Didn't get a response in time
console.log(`Got timeout in ${elapsed}ms`);
} else {
// Got a response
if (result.done) {
// Iteration complete
console.log(`Got iteration complete result in ${elapsed}ms`);
break;
}
// ...some data processing on `result.value`...
console.log(`Got result ${result.value} to process in ${elapsed}ms`);
}
}
} finally {
try {
it.return?.(); // Close the iterator if it needs closing
} catch { }
}
})();
.as-console-wrapper {
max-height: 100% !important;
}
const delay = (ms, value) => new Promise(resolve => {
setTimeout(resolve, ms, value);
});
async function* example() {
for (let i = 1; i <= 6; ++i) {
const ms = i === 1 ? 600 : Math.floor(Math.random() * 100);
await delay(ms);
yield i;
}
}
(async () => {
const asynDataStreamOrGenerator = example();
const TIMEOUT = 500; // Milliseconds
const GOT_TIMEOUT = {};
const it = asynDataStreamOrGenerator[Symbol.asyncIterator]();
try {
while (true) {
const p = it.next();
const start = Date.now();
const result = await Promise.race([p, delay(TIMEOUT, GOT_TIMEOUT)]);
const elapsed = Date.now() - start;
if (result === GOT_TIMEOUT) {
// Didn't get a response in time
console.log(`Got timeout in ${elapsed}ms`);
} else {
// Got a response
if (result.done) {
// Iteration complete
console.log(`Got iteration complete result in ${elapsed}ms`);
break;
}
// ...some data processing on `result.value`...
console.log(`Got result ${result.value} to process in ${elapsed}ms`);
}
}
} finally {
try {
it.return?.(); // Close the iterator if it needs closing
} catch { }
}
})();
.as-console-wrapper {
max-height: 100% !important;
}
await
您所做的处理(也许建立一个 promise 数组以完成该处理并在最后
Promise.all
它们)。
(async () => {
const TIMEOUT = 500; // Milliseconds
const GOT_TIMEOUT = {};
const results = [];
const it = asynDataStreamOrGenerator[Symbol.asyncIterator]();
try {
while (true) {
const p = it.next();
const result = await Promise.race([p, delay(TIMEOUT, GOT_TIMEOUT)]);
if (result === GOT_TIMEOUT) {
// Didn't get a response in time, bail
console.log("Timeout");
break;
}
// Got a response
if (result.done) {
// Iteration complete
console.log("Iteration complete");
break;
}
console.log(`Got ${result.value}`);
results.push(result.value);
}
} finally {
try {
it.return?.();
} catch { }
}
// ...code here to process the contents of `results`...
for (const value of results) {
console.log(`Process ${value}`);
}
})();
现场示例:
const delay = (ms, value) => new Promise(resolve => {
setTimeout(resolve, ms, value);
});
async function* example() {
for (let i = 1; i <= 6; ++i) {
const ms = i === 3 ? 600 : Math.floor(Math.random() * 100);
await delay(ms);
yield i;
}
}
(async () => {
const asynDataStreamOrGenerator = example(); // For the example
const TIMEOUT = 500; // Milliseconds
const GOT_TIMEOUT = {};
const results = [];
const it = asynDataStreamOrGenerator[Symbol.asyncIterator]();
try {
while (true) {
const p = it.next();
const start = Date.now();
const result = await Promise.race([p, delay(TIMEOUT, GOT_TIMEOUT)]);
const elapsed = Date.now() - start;
if (result === GOT_TIMEOUT) {
// Didn't get a response in time, bail
console.log(`Got timeout after ${elapsed}ms`);
break;
}
// Got a response
if (result.done) {
// Iteration complete
console.log(`Got iteration complete after ${elapsed}ms`);
break;
}
console.log(`Got value ${result.value} after ${elapsed}ms`);
results.push(result.value);
}
} finally {
try {
it.return?.();
} catch { }
}
// ...code here to process the contents of `results`...
for (const value of results) {
console.log(`Process ${value}`);
}
})();
.as-console-wrapper {
max-height: 100% !important;
}
const delay = (ms, value) => new Promise(resolve => {
setTimeout(resolve, ms, value);
});
async function* example() {
for (let i = 1; i <= 6; ++i) {
const ms = i === 1 ? 600 : Math.floor(Math.random() * 100);
await delay(ms);
yield i;
}
}
(async () => {
const asynDataStreamOrGenerator = example(); // For the example
const TIMEOUT = 500; // Milliseconds
const GOT_TIMEOUT = {};
const results = [];
const it = asynDataStreamOrGenerator[Symbol.asyncIterator]();
try {
while (true) {
const p = it.next();
const start = Date.now();
const result = await Promise.race([p, delay(TIMEOUT, GOT_TIMEOUT)]);
const elapsed = Date.now() - start;
if (result === GOT_TIMEOUT) {
// Didn't get a response in time, bail
console.log(`Got timeout after ${elapsed}ms`);
break;
}
// Got a response
if (result.done) {
// Iteration complete
console.log(`Got iteration complete after ${elapsed}ms`);
break;
}
console.log(`Got value ${result.value} after ${elapsed}ms`);
results.push(result.value);
}
} finally {
try {
it.return?.();
} catch { }
}
// ...code here to process the contents of `results`...
for (const value of results) {
console.log(`Process ${value}`);
}
})();
.as-console-wrapper {
max-height: 100% !important;
}
it.return?.();
与 if (it.return) { it.return(); }
如果您的环境还不支持可选链接。 catch { }
与 catch (e) { }
如果您的环境不支持可选 catch
绑定(bind)呢。 关于javascript - 如果循环未在给定时间内完成,如何打破 "for await ...of"循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69541047/
我有一个 forEach循环处理数组中的数据。在该循环中间的某个地方,我必须等待 DOM 元素的更改,获取该更改,处理它,然后才能继续处理数组。 我希望在控制台中看到这个: Preparing "aa
给定以下方法: public async Task DoSomethingAsync() { // do some work await OpenSomeFileAsync();
尝试在 .exports 中运行一个异步函数,获取 Promise,然后在下一个异步函数中使用结果,但由于某种原因,无论等待如何,第二个函数都会在第一个函数之前执行。 销售.js = const sq
谁能解释为什么 c# 5 中的异步函数需要至少有 1 个等待?我找不到明确的理由/解释。 所谓必需,是指当异步函数内部没有任何 await 调用时编译器会发出警告,但不会抛出编译错误。 来自 this
我想用 Mocha 测试异步代码. 我跟着这个教程testing-promises-with-mocha .最后,它说最好的方法是 async/await。 以下是我的代码,我打算将 setTimeo
这个问题在这里已经有了答案: How do yield and await implement flow of control in .NET? (5 个答案) How is resumption
我想在 trait 中编写异步函数,但是因为 async fn in traits 还不被支持,我试图找到等效的方法接口(interface)。这是我在 Rust nightly (2019-01-0
在 node.js 中,我有一个数据库事务,我想在 then 回调中调用一个 async 方法,但我收到错误消息 关键字“等待”已保留。 这是异步 saveImage 函数: const saveIm
我正在包装 AspNet.Identity。但有些事情让我对 TPL 感到困惑。 第一个例子: public virtual async Task RemovePasswordAsync(st
我有三个 showDialog 示例。我认为 _showAlert1 是正确的,但它使用 2 个函数来实现它。 _showAlert2 也有效,但我认为它不正确,因为我认为 showDialog 是异
我正在编写一个应该尽可能快地执行所有异步函数的函数,但是,它们中只有 5 个可以同时运行。 我想使用 Promise.race 来实现,所以实现不是最好的。问题是代码执行不会在 await 处停止。我
在 Scala 和其他编程语言中,可以使用 Futures 和 Await。 (在实际代码中,会使用例如 zip+map 而不是 Await) def b1() = Future { 1 } def
这个问题在这里已经有了答案: At the end of an async method, should I return or await? (2 个回答) 8年前关闭。 我做了一些阅读,并认为我已
我知道这是一个非常开放的问题,我深表歉意。 我可以看到 Await.ready返回 Awaitable.type而 Await.result返回 T但我仍然混淆他们。 两者有什么区别? 一个是阻塞的,
为什么等待者(GetAwaiter - 使类可等待)是结构而不是类。使用类有什么坏处吗? public struct ConfiguredTaskAwaiter : ICriticalNotifyCo
这个问题在这里已经有了答案: Why doesn't Scala's Future have a .get / get(maxDuration) method, forcing us to resor
async/await 链中的所有函数都必须使用 async/await 关键字吗? async function one() { return await fetch(.....); } asy
点击组件的按钮时将执行以下方法。 async onClickButton() { await this.shoppingCartService.add(this.selectedOffer);
它似乎被记录在案的唯一地方是 this issue thread和 the actual specification .但是,删除的原因并没有在我能找到的任何地方发布。 新的推荐方式似乎是await
为什么使用 await 需要将其外部函数声明为 async? 例如,为什么这个 mongoose 语句需要它所在的函数来返回一个 promise? async function middleware(
我是一名优秀的程序员,十分优秀!