Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8697

Node.jsのasync queueを使ってみた

$
0
0

async queueについて

  • 非同期処理を順番に実行してくれる
  • async.queueの第一引数は非同期処理
  • async.queueの第二引数はqueueを同時に実行する数
  • async.queueの返り値はqueueを表すオブジェクト

queueオブジェクトの中身

push

  • queueの最後尾にデータを追加

unshift

  • queueの最初にデータを追加

length

  • 待機しているqueueの数

running

  • 実行中のqueueの数

pause

  • queueの処理を一時停止

resume

  • queueの処理を再開

サンプルコード

const async = require('async')

// 第一引数がqueueのパラメータ、第二引数が次のqueueの処理に入るトリガー
const q = async.queue((data, callback) => {
  const obj = {
    length: q.length(),
    running: q.running(),
    data
  }
  console.log('結果', obj)
  setTimeout(() => {
    callback()
  }, 1000)
}, 1)

q.push('1')
q.push('2')
q.push('3')
q.push('4')
q.push('5')
q.unshift('0')

setTimeout(() => {
  console.log('一時停止')
  q.pause()
}, 3000)

setTimeout(() => {
  console.log('再開')
  q.resume()
}, 5000)

結果

結果 { length: 5, running: 1, data: '0' }
結果 { length: 4, running: 1, data: '1' }
結果 { length: 3, running: 1, data: '2' }
一時停止
再開
結果 { length: 2, running: 1, data: '3' }
結果 { length: 1, running: 1, data: '4' }
結果 { length: 0, running: 1, data: '5' }

queueの削除について

  • queueを追加した後にqueue内のデータを削除する処理が見当たらなかったので、queueの持っているデータとは別に同じデータを外部で保存しておいて、外部のデータ内にデータが存在すればqueueを実行するようにしました
const list = []
const queue = async.queue((data, callback) => {
    // listにデータが存在する場合のみ処理を実行
    if (list.include(data)) {
        // queueの処理を実行する
        callback()
    } else {
        callback()
    }
})

const data = 'sample'
list.push(data)
queue.push(data)

Viewing all articles
Browse latest Browse all 8697

Trending Articles