Takahashi Yuki
2019-03-26 社内勉強会資料
Mさん「なんかawaitでとまらないんですけど……
ぼく「awaitがとまらないわけないじゃん?どれどれ
export function timer (delay) {
return new Promise(resolve => {
setTimeout(() => {
console.log(`timer ${delay}ms`)
resolve()
}, delay)
})
}
import { timer } from './timer'
;[100, 300, 200].forEach(async delay => {
await timer(delay)
})
$ timer 100ms
$ timer 300ms
$ timer 200ms
$ timer 100ms
$ timer 200ms
$ timer 300ms
ぼく「うーん、これはawaitされてない🤔
async/awaitはPromiseを同期的なコードのように記述することのできる糖衣構文
非同期処理を抽象化したオブジェクト
then
で逐次処理
import { timer } from './timer'
let promiseChain = Promise.resolve()
;[100, 300, 200].forEach(delay => {
promiseChain = promiseChain.then(() => timer(delay))
})
async/awaitでも
for…ofを使えば期待通りに逐次処理される
import { timer } from './timer'
;(async () => {
for (const delay of [100, 300, 200]) {
await timer(delay)
}
})()
forEachの実装を簡略化したもの
Array.prototype.forEach = callback => {
for (let index = 0; index < this.length; index++) {
callback(this[index], index, this) // <-awaitしてない犯人
}
}
awaitするforEach
import { timer } from './timer'
async function asyncForEach (array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}
asyncForEach([100, 300, 200], async delay => {
await timer(delay)
})
import { timer } from './timer'
const result = [100, 300, 200].map(async delay => await timer(delay))
console.log(result)
[ Promise { <pending> },
Promise { <pending> },
Promise { <pending> } ]
timer 100ms
timer 200ms
timer 300ms
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing