LoginSignup
52
56

More than 5 years have passed since last update.

promiseの無限ループはメモリリークする

Last updated at Posted at 2015-12-31

promiseの無限ループはメモリリークする

注意しないとやっちゃうパターンとして。

メモリリークするパターン

const timeout = ms => new Promise((resolve, reject) => setTimeout(() => resolve(), ms))

const start = (ctx) => {
    return timeout(ctx.timer).then(() => {
        return start(ctx)
    }).catch(e => {
        return start(ctx)
    })
}

const main = () => start({timer:0})

main()
  • return start(ctx)の箇所でpromise chainができているため無限に伸びてメモリが足りなくなります

メモリリークしないパターン

const timeout = ms => new Promise((resolve, reject) => setTimeout(() => resolve(), ms))

const start = ctx => {
    timeout(ctx.timer).then(() => {
        start(ctx)
    }).catch(e => {
        start(ctx)
    })
}

const main = () => start({timer:0})

main()

ハマりやすいパターン(メモリリークするパターン)

const timeout = ms => new Promise((resolve, reject) => setTimeout(() => resolve(), ms))

const start = ctx => timeout(ctx.timer)
        .then(() => start(ctx))
        .catch(e => start(ctx))

const main = () => start({timer:0})

main()

PS

私はこれで年末~正月ハマりました
Promiseで無限ループする場合はreturnで返さずにオブジェクトに状態をもつようにするとよいです

52
56
4

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
52
56