0
0

More than 3 years have passed since last update.

[Electron, Vue.js] IpcRenderer.on()でthis.countに代入しようとしたら失敗した

Last updated at Posted at 2021-03-08

動機

ElectronのipcRenderer.on()内でthis.countに受け取った値を代入したかったのにうまく行かなかったので
解決はしたが原因がわかりません…

目次

うまくいかない例

  mounted() {
    ipcRenderer.on("setCount", (_, arg) => {
      this.count = arg;
    });
  },

うまくいく例

なかなかグロテスクなコードになりました…
thisをコールバックの外に出してみたら何故かうまく行った

  async mounted() {
    this.count = await ((): Promise<string> =>
      new Promise((resolve) => {
        ipcRenderer.on("setCount", (_, arg) => {
          resolve(arg);
        });
      }))();
  },

関数を分けるなら

  methods: {
    async waitIpcMessage(): Promise<string> {
      return new Promise((resolve) => {
        ipcRenderer.on("setCount", (_, arg) => {
          resolve(arg);
        });
      });
    }
  },
  async mounted() {
    this.count = await this.waitIpcMessage();
  }

最後に

なぜこれならうまくいくのか知っている方は教えてください...
thisが外に出てるからうまくいくっぽい?よくわかりません

話は逸れますが非同期周りの書き方ってかなり複雑ですよね

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0