Skip to content

Instantly share code, notes, and snippets.

@IKKO-Ohta
Created June 13, 2018 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IKKO-Ohta/da6eb3f432b30c29edc094011e958015 to your computer and use it in GitHub Desktop.
Save IKKO-Ohta/da6eb3f432b30c29edc094011e958015 to your computer and use it in GitHub Desktop.
myFunc
function cashImg(url){
const {ipcRenderer} = require("electron");
var cashUrl = ""
ipcRenderer.send("downloadImgSig",url);
const imgMakeTask = new Promise((resolve,reject) =>{
ipcRenderer.once("imgManagerResponsed",(event,arg) =>{
console.log("breakpoint1:",arg);
resolve(arg);
})
});
imgMakeTask.then((value) => {
console.log("breakpoint2:",value);
cashUrl = cashUrl + value;
console.log("breakpoint3:",cashUrl);
});
return cashUrl;
};
@joe-re
Copy link

joe-re commented Jun 13, 2018

ipcRenderer.onで動作するcallbackは非同期になります。
なので受け取る側も非同期で動作するコード(promiseの解決に従って動くコード)を書く必要があります。
以下にサンプルコードを書いておきます。(拡張子が.jsxだったので、Reactと推察しています。動作確認はしていませんので、動かなかったらすみません。。)

function cashImg(url){
  const {ipcRenderer} = require("electron");
  var cashUrl = ""
  ipcRenderer.send("downloadImgSig",url);
  return new Promise((resolve,reject) =>{
    ipcRenderer.once("imgManagerResponsed",(event,arg) =>{
      console.log("cashUrl:",arg);
      resolve(arg);
    })
  });
};

class Component extends React.Component {
  constructor(props) {
    super(props)
    this.state = { cashUrl: '' }
  }
  handleClick() {
    cashImg('http://example.com').then(cashUrl => {
      this.setState({ cashUrl })
    })
  }
  render () {
    return <div> <button onClick={() => this.handleClick()}>Click</button></div>
  }
}

@joe-re
Copy link

joe-re commented Jun 13, 2018

蛇足ですが、非同期処理のコードはasync/awaitというES2017で策定された構文で書くと直感的に書けます(動作は変わりません)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
使用しているElectronのバージョンにもよりますが、最新を使っていればこれも動作すると思います。

  async handleClick() {
    try {
      const cashUrl = await cashImg('http://example.com')
      this.setState({ cashUrl })
    } catch (e) {
      // error handling
    }
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment