如何在提供的代码中循环停止 ?哪些代码应处于“ STOP”状态才能在循环时停止?
当侦听器赋予 while 另一个状态时,循环仍在运行。 常量状态值保持“开始”。侦听器赋予新状态后,它不会改变。
constructor(){
events.on("imdb-scraper-engine", ({status}) =>{
this.scraper(status);
});
this.scraper('INIT');
}
async scraper(status){
while(status == 'START'){
await axios.get('https://jsonplaceholder.typicode.com/posts').then((result)=>{
console.log(result);
});
}
if((status == 'STOP')){console.log('Process was stopped');}
if((status == 'INIT')){console.log('Engine Initialized')}
}
- eidt发现我总是开始在构造函数中调用this.scraper的新进程。但是仍然想知道如何在while循环中停止。
答案 0 :(得分:0)
Try it:
constructor(){
events.on("imdb-scraper-engine", ({status}) =>{
this.scraper(status);
});
this.scraper('INIT');
}
async scraper(status){
console.log(status)
while(status == 'START' && status != 'STOP'){
console.log(status)
await axios.get('https://jsonplaceholder.typicode.com/posts').then((result)=>{
console.log(result);
});
}
if((status == 'STOP')){console.log('Process was stopped');}
if((status == 'INIT')){console.log('Engine Initialized')}
}
答案 1 :(得分:0)
根据您可能要实现的目标,我可以为您设计一个想法。
这可能无法正常工作。
theLoop; //its a variable
constructor(){
this.listenEvent();
this.scraper('INIT');
}
function listenEvent(){
events.on("imdb-scraper-engine", ({status}) =>{
if(status=='STOP'){
clearTimeout(this.theLoop);
}
this.scrapper(status);
});
}
function startWhileLoop() {
this.theLoop = setTimeout(async function(){
await axios.get('https://jsonplaceholder.typicode.com/posts').then((result)=>{
console.log(result);
});
}, 0);
}
scraper(status){
while(status == 'START'){
startWhileLoop();
}
if((status == 'STOP')){console.log('Process was stopped');}
if((status == 'INIT')){console.log('Engine Initialized')}
}