我在for循环中编写了查询:
for (var i = 0; i < 1000; i++) {
(function(result, type, i) {
var sleepTime = 0;
if (i % 10 === 0) {
sleepTime = 3000;
console.log('reached');
}
setTimeout(function() {
prepareCache(i, result, req, res, type);
}, sleepTime);
})(result, type, i);
}
我希望每10个i停止执行prepareCache
功能3秒。即10,20,30,但是我写的代码不起作用。有人可以建议我帮忙吗?
答案 0 :(得分:0)
您应该选择Promise
。要在循环中嵌入promise,您可以检查以下代码示例:
(function loop(i) {
const promise = new Promise((resolve, reject) => {
const timeout = Math.random() * 1000;
setTimeout( () => {
console.log(i);
resolve(); // resolve it!
}, timeout);
}).then( () => i >= 10 || loop(i+1) );
})(0);