gpt4 book ai didi

javascript - Casperjs,如何仅在收到ajax调用的响应后继续

转载 作者:行者123 更新时间:2023-12-02 18:10:12 24 4
gpt4 key购买 nike

我希望 casperjs 进行 ajax 调用,但等待服务器的结果。这可能需要长达 3 分钟的时间,但通过查看脚本的运行结果我可以看出,casper.then 函数超时并在 30 秒后继续运行。我尝试将 casper.options.waitTimeout = 180000/* 3 分钟 */;在我的代码中,它确实有效,并且我尝试使用这段代码,无论我的 api 调用结果如何,它似乎每次都会等待 3 分钟。

我还知道,无论如何,评估函数每次都只返回一个 bool 值,而这不起作用,因为我需要在脚本的其余部分返回的 api 调用数据。我怎样才能让这个功能等待3分钟?幕后发生了很多事情,所以是的,我需要等这么久。

var casper = require('casper').create();

casper.start('mysite.html', function() {
});

casper.then(function() {
result = getSomethingFromMyServerViaAjax( theId );
});

这是我尝试过的替代方法,无论 ajax 调用返回的速度如何,它似乎总是等待 3 分钟。

casper.waitFor(function check() {
return this.evaluate(function() {
return result = getSomethingFromMyServerViaAjax( theId ) /* this takes up to 3 minutes */;
});
}, function then() {
casper.log("Doing something after the ajax call...", "info");
this.die("Stopping here for now", "error");
}, 180000 );

我已经在其他地方测试了我的 ajax 调用,只要响应在 30 秒内返回,它就可以工作,但如果它没有 casper,则跳过该 block 并每次都继续进行。

最佳答案

你就快到了。您需要触发长时间运行的调用。看起来它是同步的,所以我把它放在setTimeout里面。一段时间后,结果会写入 window.resultFromMyServerViaAjax 中。

this.evaluate 也是同步的,但执行后,会调度 wait 步骤并定期测试窗口属性是否已设置。

var casper = require('casper').create(),
theId = "#whatever";

casper.start('mysite.html');

casper.then(function() {
// trigger
this.evaluate(function(theId){
window.resultFromMyServerViaAjax = null;
setTimeout(function(){
window.resultFromMyServerViaAjax = getSomethingFromMyServerViaAjax(theId);
}, 0);
}, theId);
this.waitFor(function check() {
return this.evaluate(function() {
return !!window.resultFromMyServerViaAjax;
});
}, function then() {
casper.log("Doing something after the ajax call...", "info");
}, function onTimeout() {
this.die("Stopping here for now", "error");
}, 180000 );
});
casper.run();

关于javascript - Casperjs,如何仅在收到ajax调用的响应后继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19779610/

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