![](/img/trans.png)
[英]How to make a watcher run only once per digest cycle, no matter how many times the property changes
[英]Create a function that no matter how many times invoked run only when first async call finishes?
假设我有一个函数fetch(id)
。
我会在任意时间随意称呼它。
但是我希望每个后续呼叫仅在上一个呼叫完成后才运行。
说异步任务需要4秒钟,我叫fetch
3次。 那么总时间应该是12秒。
我可以创建一个数组,并且在每个调用集处都保证会依次通过下一个。
但是有什么方法可以做到这一点。
我想我明白了
//First my example function which could be anything but should return promise which would be queued
function example(n) {
return new Promise((res, rej) => {
setTimeout(()=> {
console.log(n);
res();
}, 1000);
});
}
//now solution
function debounce(func) {
let p = Promise.resolve();
return function(x){
p = p.then(() => func(x));
}
}
//usage
d = debounce(example);
d(1);d(2);d(3);d(4);d(5);d(6);d(1);
您可以在没有数组的情况下链接Promises,只需存储指向最后一个Promise的指针
// async payload function
// returns a promise
function f(x) {
console.log(`call f(${x})`);
return new Promise((resolve) => {
setTimeout(() => {
console.log(`resolve f(${x})`);
resolve();
}, 2000);
});
}
// wrapper to call function `f` sequentially
// stores pointer to the last Promise in closure
const g = (function(){
let lastPromise = Promise.resolve();
return function(arg){
lastPromise = lastPromise.then(() => f(arg));
}
})();
// generate random calls of function function `g`
for (let i = 0; i < 5; i++) {
setTimeout(() => g(i), Math.random() * 100);
}
我猜你可以使用async.io库。 或者,每次您要调用函数时,请将函数本身推入数组。 前一个函数完成后,检查数组中是否还有一些函数要调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.