【发布时间】:2017-07-23 11:46:48
【问题描述】:
背景
我正在尝试创建一个将异步函数的执行延迟 X 毫秒的函数。
出于本演示的目的,以下是异步函数,它接受一个 URL:
/*
* This is a simulation of an async function. Be imaginative!
*/
let asyncMock = function(url) {
return new Promise(fulfil => {
setTimeout(() => {
fulfil({
url,
data: "banana"
});
}, 10000);
});
};
目标
我的目标是有一个函数,它将接受 asyncMock 的 url 参数,然后每 X 毫秒调用一次,或者直到没有更多参数为止。
基本上,我希望asyncMock 的每次调用都用 X 毫秒分隔。
例如,假设我连续调用asyncMock 20 次。通常,这 20 个电话会立即完成。我想要的是确保 20 次通话之间有 Xms 的延迟。
暂定
我解决这个问题的想法是建立一个工厂,它将返回一个promise,它将在 X 毫秒后执行该函数。
let throttleFactory = function(args) {
let {
throttleMs
} = args;
let promise = Promise.resolve();
let throttleAsync = function(url) {
return promise.then(() => {
setTimeout(anUrl => {
return new Promise( fulfil => {
fulfil(asyncMock(anUrl));
});
}, throttleMs, url);
});
};
return Object.freeze({
throttleAsync
});
};
理想情况下,我会像下面的示例一样使用这个工厂:
let throttleFuns = throttleFactory({
throttleMs: 2000
});
console.log('running');
throttleFuns.throttleAsync('http://www.bananas.pt')
.then(console.log)
.catch(console.error);
throttleFuns.throttleAsync('http://www.fruits.es')
.then(console.log)
.catch(console.error);
throttleFuns.throttleAsync('http://www.veggies.com')
.then(console.log)
.catch(console.error);
// a ton of other calls in random places in code
问题
这里的问题是我的throttleAsync 函数立即输出了三遍undefined。我相信这可能是因为我没有正确定义promise。
问题
如何修复此代码以按预期工作?
【问题讨论】:
-
除了承诺问题之外,我看不出这是如何限制的。它会延迟事情,但不会扼杀它们。
-
好的,也许我应该更改描述?我在上面。
-
更新描述,感谢反馈!
标签: javascript node.js ecmascript-6 promise