Javascript Promise返回值 [英] Javascript Promise return value
问题描述
我正在尝试制作搜寻器,由于页面源中未显示数据,因此只能使用Web驱动程序执行javascript并获取响应,然后进行数据分析。
脚本经过简化,像这样,使用Promise。
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. The script is simplified, like this, use 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
我的程序就是这样,用c#编写:
My program is like this, writing with 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();
}
我想获取价值,我知道然后
总是返回Promise对象,因此我定义了一个变量,并希望将值存储到该变量。但是,似乎Promise是异步执行的,因此res始终为空。
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. But seems that, the Promise is executed asynchronous, so the res always be empty.
好的,我正在编写一个搜寻器,并使用Selenium来获取响应。服务器(Selenium.webdriver可以打开Web浏览器,然后执行脚本),我需要获取结果,因为它将被另一个程序使用。因此,我不能只添加另一个.the,而只需输出值。也许我可以保存到本地文件,然后阅读它,但是我认为它效率低下。
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. So, I can not just add another .then, just output the value. Maybe I can save to a local file, and then read it, but I think it is inefficient.
任何人都可以提供帮助吗?
Anyone can help?
推荐答案
尝试一下
您使用的诺言不正确。
Try this You're using promises incorrectly.
f1()。然后(res => console.log('result =',res))。
这篇关于Javascript Promise返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!