背景
我正在尝试创建一个函数,将异步函数的执行延迟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 毫秒。
例如,假设我连续调用了 20 次 asyncMock
。通常情况下,这些 20 次调用会立即执行。但我想要的是,在这 20 次调用之间每个调用之间都有 Xms 的延迟。
设想
我的解决思路是创建一个工厂,返回一个promise,该 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
。
问题
我该如何修改此代码以使其按预期工作?