gpt4 book ai didi

javascript - 如何仅使用 native Promise 编写异步计数器,即具有用于异步代码的同步接口(interface)的计数器?

转载 作者:行者123 更新时间:2023-11-28 14:27:58 26 4
gpt4 key购买 nike

我想创建一个公开以下接口(interface)的对象:

// Create the object that counts to three
const c = counter(3);
// c.finished is a promise that resolves when c.count() is invoked three times
c.finished.then(() => console.log('counted three times!'));

// Somewhere else, c.count() is invoked in async body
setTimeout(() => c.count(), 500);
setTimeout(() => c.count(), 1000);
setTimeout(() => c.count(), 1500);

我预计 c.finished 在 1.5 秒后解析。

如何仅使用 native Promise API 编写 counter(countTimes)

披露我已经有 a solution对于上面的问题,想知道最优雅的方法是什么。

编辑

我原来的解决方案是:

class AsyncCounter {
constructor(countTimes) {
let currentCount = 0;
this.countTimes = countTimes;
this.ready = new Promise(resolveReady => {
this.finished = new Promise(resolveFinished => {
const count = () => {
currentCount++;
if (currentCount >= this.countTimes) {
resolveFinished();
}
return currentCount;
};
this.count = () => this.ready.then(() => count());
resolveReady();
});
});
}
}

const counter = countTimes => new AsyncCounter(countTimes);

按照@Bergi的建议并根据MDN docs for executor function :

the executor is called before the Promise constructor even returns the created object

因此,上述解决方案中的 ready promise 并不是必需的。

最佳答案

你会写

function counter(n) {
let i=0, resolve;
return {
count() {
if (++i == n) resolve();
},
finished: new Promise(res => {
resolve = res;
})
};
}

或者,您也可以不将 resolve 放入外部变量中

function counter(n) {
let i=0;
const res = {};
res.finished = new Promise(resolve => {
res.count = () => {
if (++i == n) resolve();
};
});
return res;
}

关于javascript - 如何仅使用 native Promise 编写异步计数器,即具有用于异步代码的同步接口(interface)的计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52517770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com