2014-11-17 6 views
0

Я очень новичок в JS и функциональном программировании в целом и изо всех сил стараюсь найти изящное решение этой проблемы. По сути, я хочу сделать асинхронные запросы на сервер MongoDB и вернуть результаты функции async to map. Проблема, которую я испытываю в том, что фактическая функция в пределах async.map является асинхронной. Я хотел бы знать изящное решение здесь или, по крайней мере, получить указатель в правильном направлении! Благодаря!Сохранение результата асинхронной функции в Async.map

async.map(subQuery, 
    function(item){ 
     collection.distinct("author", item, function(err, authors){ 
     counter++; 
     console.log("Finished query: " + counter); 

     var key = item['subreddit']; 
     return { key: authors }; 
     }) 
    }, 

    function(err, result){ 
     if (err) 
     console.log(err); 
     else{ 
     console.log("Preparing to write to file..."); 

     fs.writeFile("michaAggregate.json", result, function() { 
      console.log("The file was saved!"); 
     }); 
     } 

     db.close(); 
    } 
); 

ответ

1

Вы должны обрабатывать элемент только при извлечении данных. Просто используйте обратный вызов. Это обычный способ JavaScript. Как это:

var processItem = function(item){ 
// Do some street magic with your data to process it 

// Your callback function that will be called when item is processed. 
onItemProccessed(); 
} 

async.map(subQuery, 
function(item){ 
    collection.distinct("author", item, function(err, authors){ 
    counter++; 
    console.log("Finished query: " + counter); 

    var key = item['subreddit']; 
    processItem(item); 
    }) 
}, 

function(err, result){ 
    if (err) 
    console.log(err); 
    else{ 
    // That string added **ADDED** 
    console.log('HEEY! I done with processing all data so now I can do what I want!'); 
    console.log("Preparing to write to file..."); 

    fs.writeFile("michaAggregate.json", result, function() { 
     console.log("The file was saved!"); 
    }); 
    } 

    db.close(); 
} 
); 

ДОБАВЛЕНО

По спецификации async.map вы можете увидеть:

https://github.com/caolan/async

async.map(arr, iterator, callback):

callback(err, results) - A callback which is called when all iterator functions have finished, or an error occurs. Results is an array of the transformed items from the arr. Как вы видите, что обратный вызов именно то, что вы необходимость!

+0

Хорошо. В этом случае, как я мог бы что-то сделать, как только я обработал все это? – ianks

+0

В конце 'processItem()' просто вызовите нужную функцию – Maris

+0

Это будет называть n раз, правда, правильно? Я просто хочу позвонить ему один раз. – ianks

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