简体   繁体   English

我如何防止没有箭头功能的承诺丢失上下文

[英]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.

相关问题 如何在没有承诺的情况下从 function 捕获异步错误? - How do I catch an asynchronous error from a function without promises? 如何在不丢失上下文的情况下与JSP页面共享javascript? - How do i share javascript with JSP pages without losing context? 当被调用函数本身在上下文中时,如何避免nodejs vm脚本函数调用丢失上下文? - How do I avoid nodejs vm script function call losing context when called function is itself in the context? 我如何在没有承诺的情况下在异步函数中读取文件? - How do I read a file in an async function without promises? 如何从箭头功能提醒多个回调结果? - How do I alert multiple results of a callback from an arrow function? 如何从此箭头函数返回 pkgInfo 对象? - How do I return the pkgInfo object from this arrow function? 如何使用 Promise 重写函数? - How do I rewrite a function using promises? 如何在不更改功能结构的情况下保留上下文? - How do I keep the context without changing the structure of function? 如何在没有在执行程序函数中添加事件处理程序的情况下将 Promise 与“click”事件一起使用? - How do I use Promises with ´click´ events without adding event handler in the executor function? 我如何阅读以下箭头功能 - How do I read the following arrow function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM