因为
throttleAsync返回调用的结果
promise.then,并且
then回调不返回任何内容。这使得通过
then解决创造的承诺具有价值
undefined。
您可能打算让它返回您正在创建的新的Promise,但是直到
setTimeout回调之前您都不会这样做。您想事先做(但还有更多,请继续阅读):
let throttleAsync = function(url) { return promise.then(() => { return new Promise( fulfil => { setTimeout(anUrl => { fulfil(asyncMock(anUrl)); }, throttleMs, url); }); });};也没有理由
setTimeout像这样传递URL ,因此:
let throttleAsync = function(url) { return promise.then(() => { return new Promise( fulfil => { setTimeout(() => { fulfil(asyncMock(url)); }, throttleMs); }); });};最初,我虽然
promise没有必要,但是您已经澄清了,您想确保重复的呼叫由隔开
throttleMs。为此,我们将使用上面的方法,但要进行更新
promise:
let throttleAsync = function(url) { return promise = promise.then(() => { // ^^^^^^^^^ return new Promise( fulfil => { setTimeout(() => { fulfil(asyncMock(url)); }, throttleMs); }); });};这样,下一个呼叫
asyncThrottle将一直等到前一个触发后再开始下一个。
现场示例:
const throttleMs = 1000;const asyncMock = url => url;let promise = Promise.resolve();let throttleAsync = function(url) { return promise = promise.then(() => { // ^^^^^^^^^ return new Promise( fulfil => { setTimeout(() => { fulfil(asyncMock(url)); }, throttleMs); }); });};console.log('running');throttleAsync('http://www.bananas.pt') .then(console.log) .catch(console.error);throttleAsync('http://www.fruits.es') .then(console.log) .catch(console.error);throttleAsync('http://www.veggies.com') .then(console.log) .catch(console.error);


