[英]Javascript Promise return value
I am trying to make a crawler, and as the data is not showing in the page source, I can only execute the javascript with the web driver and get the response, and then do the data analysis. 我正在尝试制作搜寻器,并且由于数据未显示在页面源中,所以我只能使用Web驱动程序执行javascript并获取响应,然后进行数据分析。 The script is simplified, like this, use Promise.
脚本被简化,像这样,使用Promise。
var res = ""
function f1() {
p = window.Promise
a = p.resolve(5).then(function(value) {
console.log(value)
res = value
return res
})
return a
}
console.log(f1()) // Promise object
console.log("result = ", res) // res is empty
My program is like this, writing with c#: 我的程序就是这样,用c#编写:
public void GetParameters(string url)
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl(url);
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
string script = readFile(@"C:\myscript.js", Encoding.UTF8).TrimEnd(); // The script is a bit long, so I save it to a local file.
var json = js.ExecuteScript(script);
Console.WriteLine("Get the return value");
Console.WriteLine(json);
driver.Close();
}
I want to get the value, and I know then
always return Promise object, so I define a variable, and want to store the value to it. 我想要得到的价值,我知道
then
总是返回无极对象,所以我定义一个变量,并希望将值存储到它。 But seems that, the Promise is executed asynchronous, so the res always be empty. 但是似乎Promise是异步执行的,因此res始终为空。
OK, I'm writing a crawler, and use Selenium to get the response from the server (Selenium.webdriver can open a web browser, and then execute script), I need get the result, as it will use by another program. 好的,我正在编写一个搜寻器,并使用Selenium从服务器获取响应(Selenium.webdriver可以打开Web浏览器,然后执行脚本),我需要获取结果,因为它将被另一个程序使用。 So, I can not just add another .then, just output the value.
因此,我不能只添加另一个.the,而只需输出值。 Maybe I can save to a local file, and then read it, but I think it is inefficient.
也许我可以将其保存到本地文件,然后读取它,但是我认为它效率低下。
Anyone can help? 有人可以帮忙吗?
When you try to log the global res
, the result hasn't been computed yet. 当您尝试记录全局
res
,尚未计算结果。 When using Promises, you have to get the result asynchronously, using .then
, like this: 使用Promises时,必须使用
.then
异步获取结果,如下所示:
f1().then(res => console.log("result =", res));
试试这个,您使用的诺言不正确。
f1().then(res => console.log('result=', res)).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.