gpt4 book ai didi

javascript - JS : Using Asynchronous Functions to Pause Operation

转载 作者:行者123 更新时间:2023-11-30 06:21:16 26 4
gpt4 key购买 nike

我正在为 Google 搜索结果创建一个网络扫描仪。我希望用户能够在搜索结果时暂停程序。最初我尝试使用 while 循环暂停它,但是因为 JS 是单线程的,所以这会卡住程序。我被告知我可以使用 Promises 解决这个问题,但代码在暂停时仍然卡住,我无法恢复程序。

我怎样才能正确地使这项工作异步进行?

var pause = false;
var q = 'query';
fetchUrls(q);

function fetchUrls(q, page = 0) {
PAUSE().then(function () {
request(`https://www.google.com/search?q=${q}&start=${page}`, (error, response, htmlString) => {
if (!error && response.statusCode == 200) {
// Do whatever I want with the page data
page += 10;
fetchUrls(q, page);
}
});
});
}

function PAUSE() {
return new Promise(resolve => {
if (pause) {
$('.pause-button').addClass('hidden');
$('.resume-button').removeClass('hidden');
}
// Pause the program
while (pause) {
}
$('.pause-button').removeClass('hidden');
$('.resume-button').addClass('hidden');
resolve(true);
});
}

$(document).on('click', '.pause-button', function() {
pause = true;
});

$(document).on('click', '.resume-button', function() {
pause = false;
});

最佳答案

处理状态很困难,为此我建议您使用像 react 这样的现代框架。这也将帮助您构建代码。

学习promises,我想你已经把then的 Angular 色和promise任务调换了。

// this should be maybe on the promise creator
request(`https://www.google.com/search?q=${q}&start=${page}`, (error, response, htmlString) => {
if (!error && response.statusCode == 200) {
// Do whatever I want with the page data
page += 10;
// fake the request to test it in isolation
fetchUrls(q, page);
}
});


// this should be when resolving, on the method .then
return new Promise(resolve => {
if (pause) {
$('.pause-button').addClass('hidden');
$('.resume-button').removeClass('hidden');
}
// Pause the program
while (pause) {
}
$('.pause-button').removeClass('hidden');
$('.resume-button').addClass('hidden');
resolve(true);
});

本主题: promise 、回调、状态更改并不容易...

我已经为您的代码创建了一个工作版本,其中包含模拟请求的功能,这意味着进行虚假请求。正如我所说,我希望这能帮助您澄清一些概念。即使您想将此代码转换回原始 javascript。

const fakeRequest = (url,callback) => {
const time = 300 + Math.random()*1800;
console.log("Fetching "+url+" ...");
setTimeout(() => {
console.log("Elapsed "+Math.round(time)+"ms");
let error,response = {};
if (Math.random() > 0.1){
error = false;
response.statusCode = 200;
}else{
error = true;
}
callback(error,response,'<HTML/>');
},time);
};



class UrlFetcher extends React.Component {
constructor() {
super();
this.state = {paused:true, page:0};
//this.handleOnChange = this.handleOnChange.bind(this);
}


onClick() {
return () => {
if (this.state.paused)
this.fetchUrls('query');
this.setState((state, props) => {
state.paused = !state.paused;
return state;
});

}
}

fetchUrls(q) {
console.log('Promising');
return new Promise((resolve,reject) => {
fakeRequest(`https://www.google.com/search?q=${q}&start=${this.state.page}`, (error, response, htmlString) => {
if (!error && response.statusCode == 200) {
// Do whatever I want with the page data
console.log("Request HIT");
resolve(true);
}else{
console.log("Request FAILED");
resolve(false);
}
});

}).then(()=>{
if (!this.state.paused){
this.setState((state, props) => {
state.page += 10
return state;
});

this.fetchUrls(q);
}
});
}

render() {

const btnStates = {
true : {text: 'Launch', class: 'launch-button'},
false : {text: 'Pause', class: 'pause-button'}
};
const btn = btnStates[this.state.paused];

return (
<button class={btn.class} onClick={this.onClick()}>
{btn.text}
</button>

)
}
}

ReactDOM.render(<UrlFetcher />, document.getElementById('urlfetcher'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="urlfetcher"></div>

关于javascript - JS : Using Asynchronous Functions to Pause Operation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52912333/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com