2014-02-15 2 views
1

Я обрабатываю большое количество заданий, а затем записываю их в базу данных. Рабочий процесс является то, что:NodeJS: Нарушение большого количества синхронных задач в задачах async

  1. Читайте о 100 MB данных в буфер
  2. Loop через данные, а затем обработать (синхронизации работы) и запись на диск (асинхронная работа)

Проблемы Я имея это, он завершит цикл по всем 100 MB данных и тем временем поставит в очередь всю запись на диск за циклом событий. Таким образом, он сначала перебирает все данные, а затем запускает работу async.

Я хотел бы разбить синхронную задачу итерации по массиву, чтобы каждая итерация попадала в очередь за циклом события.

var lotsOfWorkToBeDone = ['tens of thousands of job', 'tens of thousands of job', 'tens of thousands of job', 'tens of thousands of job', 'tens of thousands of job', 'tens of thousands of job', 'tens of thousands of job'] 

while (true) { 
    var job = lotsOfWorkToBeDone.pop() 
    if (!job) { 
    break 
    } 
    var syncResult = syncWork(job) 
    asyncWork(syncResult) 
} 

function syncWork(job) { 
    console.log('sync work:', job) 
    return 'Sync Result of ' + job 
}; 

function asyncWork(syncResult) { 
    setTimeout(function() { 
    console.log('async work: ', syncResult) 
    }, 0) 
} 


// Desire Outcome 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 

// Actual Outcome 
// sync work: tens of thousands of job 
// sync work: tens of thousands of job 
// sync work: tens of thousands of job 
// sync work: tens of thousands of job 
// sync work: tens of thousands of job 
// sync work: tens of thousands of job 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// async work: Sync Result of tens of thousands of job 

Примечание: пример упрощенной версии реальности. У меня нет массива, через который я могу выполнить итерацию. И у меня есть большой буфер, и я обрабатываю до EOF (следовательно, цикл while)

+0

Не удается выполнить задание для построения массива с элементами буфера, а затем повторить итерацию этого массива с помощью async.foreach? – fmodos

+0

Собственно, это может быть хорошей идеей. – samol

+0

Да, я думаю, что это единственное решение, потому что кажется, что вы не можете перебирать буфер асинхронным способом, дайте мне знать, если он работает, а затем я могу отправить ответ – fmodos

ответ

2

Использование async.whilst, похоже, для достижения желаемого результата.

На данный момент я не принимаю свой собственный ответ, так как меня интересуют, какие комментарии люди хотели бы сделать на этом решении. Может быть лучшее решение

var async = require('async') 
var lotsOfWorkToBeDone = ['tens of thousands of job', 'tens of thousands of job', 'tens of thousands of job', 'tens of thousands of job', 'tens of thousands of job', 'tens of thousands of job', 'tens of thousands of job'] 

var job; 
async.whilst(function() { 
    job = lotsOfWorkToBeDone.pop() 
    return job 
}, function(callback) { 
    var syncResult = syncWork(job) 
    asyncWork(syncResult, callback) 
}, function(err) { 
    console.log('error: ', err) 
}) 

function syncWork(job) { 
    console.log('sync work:', job) 
    return 'Sync Result of ' + job 
}; 

function asyncWork(syncResult, callback) { 
    setTimeout(function() { 
    console.log('async work: ', syncResult) 
    callback() 
    }, 0) 
} 

// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
// sync work: tens of thousands of job 
// async work: Sync Result of tens of thousands of job 
0

Рассмотрите возможность использования потоков. Буферизация 100 МБ звучит как плохая идея. Окончательный код будет выглядеть примерно так:

inputStream.pipe(yourTransformStream).pipe(outputStream); 

вся логика будет реализовывать в качестве Transform потока.

+0

Я, конечно же, подумал об этом. Но поскольку длинный список причин из-за зависимостей, я на самом деле не могу использовать потоки – samol

Смежные вопросы