我正试图让我的头脑围绕着 promise ,但我收到此错误,提示未处理的 promise 拒绝,但如果它被拒绝,我确实有一个catch
!
任何人都可以帮我解决我做错的事情吗?
这是我的代码:
var webdriver = require('selenium-webdriver');
function searchTextOnGoogle() {
var driver = new webdriver.Builder().forBrowser("chrome").build();
driver.get("www.google.com").then(function() {
driver.findElement(webdriver.By.linkText("Automation")).click().then(function() {
driver.getTitle().then(function(title) {
setTimeout(() => {
console.log(title);
driver.quit();
}, 5000);
});
}).catch(function(err) {
console.log(err);
});
});
}
错误:
(node:200092) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:200092) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
整个错误消息:
DevTools listening on ws://127.0.0.1:62260/devtools/browser/6dd5b3dc-f6bb-4147-9421-a6e0e172017b(node:191496) UnhandledPromiseRejectionWarning: InvalidArgumentError: invalid argument (Session info: chrome=79.0.3945.117) at Object.throwDecodedError (C:\promise\node_modules\selenium-webdriver\lib\error.js:550:15) at parseHttpResponse (C:\promise\node_modules\selenium-webdriver\lib\http.js:563:13) at Executor.execute (C:\promise\node_modules\selenium-webdriver\lib\http.js:489:26) at processTicksAndRejections (internal/process/task_queues.js:93:5) at async thenableWebDriverProxy.execute (C:\promise\node_modules\selenium-webdriver\lib\webdriver.js:699:17) (node:191496) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:191496) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
最佳答案
无论抛出什么,如果您有 searchTextOnGoogle
返回一个与内部所有异步操作正确链接的 Promise,然后在调用 时调用
,所有错误都应该被正确捕获。使用异步函数也可以使内容更具可读性:.catch
searchTextOnGoogle
const delay = ms => new Promise(res => setTimeout(res, ms));
async function searchTextOnGoogle() {
var driver = new webdriver.Builder().forBrowser("chrome").build();
await driver.get("www.google.com");
await driver.findElement(webdriver.By.linkText("Automation")).click();
const title = await driver.getTitle();
await delay(5000);
console.log(title);
await driver.quit();
}
searchTextOnGoogle()
.catch(console.log);
请注意,.quit
也返回一个 Promise,并且您需要将 setTimeout
内的异步操作与外部 Promise 链正确链接。
该错误可能是由以下行引起的:
driver.get("www.google.com");
docs say .get
的参数应该是完全限定的 URL,因此解决方案可能是将其更改为:
driver.get("https://www.google.com");
或者类似的东西。
关于javascript - 如何处理 "promise rejections are deprecated",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60106489/