Upgrade to Pro — share decks privately, control downloads, hide ads and more …

AsyncStorageをNodeのREPLから操作するためにTop-levelでawaitし...

joe_re
July 14, 2017

 AsyncStorageをNodeのREPLから操作するためにTop-levelでawaitしたい人生だった

五反田.js #8 LT資料

joe_re

July 14, 2017
Tweet

More Decks by joe_re

Other Decks in Technology

Transcript

  1. Example Persisting date: try { await AsyncStorage.setItem('@MySuperStore:key', 'I like to

    save it.'); } catch (error) { // Error saving data } Fetching date: try { const value = await AsyncStorage.getItem('@MySuperStore:key'); if (value !== null){ // We have data!! console.log(value); } } catch (error) { // Error retrieving data }
  2. Node.js ではTop Level で非同期処理の 結果を扱えない 人類はES2017 よりasync/await を獲得したが、 await はasync

    function の中でしか使えない // ng function request { const response = await fetch( '/data.json' ); const json = await response.json(); const result = await hydrateSomehow(json); return result; } // ok function async request { const response = await fetch( '/data.json' ); const json = await response.json(); const result = await hydrateSomehow(json); return result; }
  3. REPL で Promise オブジェクトを 扱おうとすると.. > let out = null;

    > promiseObj.then((res) => { out = res }); > out // finally available here
  4. Top­level await is a footgun https://gist.github.com/Rich­ Harris/0b6f317657f5167663b493c722647221 Top­level のawait を許すと1

    つの依存を解決するだけでも、 その先の関係のない処理まで止めざるを得ない await は直列を強要するので、ネットワークを介した処理の 並列化ができない
  5. Example(borrow from Harris) // main.js import './foo.js'; import './bar.js'; //

    foo.js await delay( Math.random() * 1000 ); console.log( 'foo happened' ); // bar.js await delay( Math.random() * 1000 ); console.log( 'bar happened' );
  6. 今回はこのような実装に _resolveMessageFromRN(fileName) { let json = {}; let received =

    false; for (let i = 0; i < this.timeout; i++) { sleep.msleep(100); const fileContent = fs.readFileSync(fileName, 'utf8'); if (fileContent) { json = JSON.parse(fileContent); delete this.que[Number(json.queId)]; received = true; break; } sleep.msleep(900); } fs.unlinkSync(fileName); if (!received) { throw new Error("can't receive response from ReactNative Application"); } if (json.error === 1) { throw new Error(json.message); } return json.result; }