[英]How do I prevent promises from losing context without arrow function
I have the following code... 我有以下代码...
page.goToPage().then(() => page.isLoaded()).then(() => driver.quit());
This seems to be too verbose but when I try... 这似乎太冗长,但是当我尝试...
page.goToPage().then(page.isLoaded).then(driver.quit);
I get errors because in page.isLoaded
the context of this
changes to the promise. 我得到的错误,因为在
page.isLoaded
的背景下this
改变的承诺。
Is there a way I can do the later without an arrow function? 有没有办法不用箭头功能就可以做以后的事情?
Use promises properly. 正确使用承诺。 There is nothing too verbose about arrow notation, but a good practice is to make sure that any
then
handler is provided with the information it needs to do the job you need it to do. 箭头符号没有什么太冗长的,但是一个好的实践是确保向
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"));
}
});
}
}
Now, you have proper promise-using code: 现在,您具有适当的使用promise的代码:
var p = new Page();
p.goToPage()
.then( page => page.waitForLoad())
.then( driver => driver.quit())
.catch( e => console.error(e));
Each then
handler now gets exactly the input it needs to call the functions it needs to call, without trying to bust through their own scope, and without having to .bind()
anything. 每个
then
处理现在得到它到底需要调用它需要调用的函数,没有试图通过自己的范围,胸围的输入,而不必.bind()
什么。
(If you need .bind()
in normal code, that's usually the sign you are fighting against JavaScript in terms of ensuring sope, rather than making use of the various ways JavaScript lets you ensure correct scope) (如果您需要普通代码中的
.bind()
,通常这就是您在确保Sope方面与JavaScript作战的标志,而不是利用JavaScript可以确保正确范围的各种方式)
Like Mike suggested after finding the answer it doesn't seem any less verbose... 就像迈克(Mike)在找到答案后建议的那样,它似乎并不那么冗长...
page.goToPage()
.then(page.isLoaded.bind(page))
.then(driver.quit.bind(driver));
(Thanks @GetOffMyLawn) (感谢@GetOffMyLawn)
I will leave the question unanswered in case someone has a creative solution. 如果有人有创造性的解决方案,我将不回答这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.