1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Greenletを試す

Posted at

developit/greenlet: 🦎 Move an async function into its own thread.

Greenletは単純に言うと、WebWorkerをシンプルに扱えるようにしたライブラリ。

Web Workers API - Web API インターフェイス | MDN

index.html
<script src="https://unpkg.com/greenlet@0.1.2/dist/greenlet.umd.js"></script>
<script>
const getName = greenlet(async username => {
  const url = `https://api.github.com/users/${username}`
  const res = await fetch(url)
  const profile = await res.json()
  return profile
})

getName('akameco').then(console.log).catch(console.error);
</script>

面倒なので、何も考えずparcelで

$ parcel index.html

DevtoolのConsoleタブで開くと結果が得られているのがわかると思う。
また、SourcesタブのNetworkを見ると、差し込まれたWorkerがわかる。

ちなみに実装的にgreenletおよびWorkerのコードにブレークポイントを置いても、greenletの実装的にデバッグするのは不可能。

どうなっているかというと、関数を文字列としてdata URIにするという実装をしている。
ここまで書くとわかるようにスコープ外の変数はもちろん使えない。(まあWebWorkerなので当たり前だけど)

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?