![](/img/trans.png)
[英]How do I catch an asynchronous error from a function without promises?
[英]How do I prevent promises from losing context without arrow function
我有以下代碼...
page.goToPage().then(() => page.isLoaded()).then(() => driver.quit());
這似乎太冗長,但是當我嘗試...
page.goToPage().then(page.isLoaded).then(driver.quit);
我得到的錯誤,因為在page.isLoaded
的背景下this
改變的承諾。
有沒有辦法不用箭頭功能就可以做以后的事情?
正確使用承諾。 箭頭符號沒有什么太冗長的,但是一個好的實踐是確保向then
任何處理程序提供執行任務所需的信息。
class Driver {
quit() {
console.log("quit");
}
}
class Page {
constructor() {
this.driver = new Driver();
}
goToPage() {
console.log("gotopage");
return new Promise((resolve, reject) => {
// Things happen here. If they go wrong, you call reject() with an argument that
// is a useful error object. If they succeed, you call resolve() with data that the
// next handler should be working with. In this case I'm passing "this" so that the
// page is available to the next link in the chain.
resolve(this);
});
}
waitForLoad() {
console.log("waitforload");
return new Promise((resolve, reject) => {
// let's have this fail half the time, for demonstration purposes.
var l = Math.random();
if (l < 0.5) {
resolve(this.driver);
} else {
reject(new Error("error"));
}
});
}
}
現在,您具有適當的使用promise的代碼:
var p = new Page();
p.goToPage()
.then( page => page.waitForLoad())
.then( driver => driver.quit())
.catch( e => console.error(e));
每個then
處理現在得到它到底需要調用它需要調用的函數,沒有試圖通過自己的范圍,胸圍的輸入,而不必.bind()
什么。
(如果您需要普通代碼中的.bind()
,通常這就是您在確保Sope方面與JavaScript作戰的標志,而不是利用JavaScript可以確保正確范圍的各種方式)
就像邁克(Mike)在找到答案后建議的那樣,它似乎並不那么冗長...
page.goToPage()
.then(page.isLoaded.bind(page))
.then(driver.quit.bind(driver));
(感謝@GetOffMyLawn)
如果有人有創造性的解決方案,我將不回答這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.