簡體   English   中英

如何在async.each完成之前延遲一個承諾?

[英]How to delay a promise until async.each completes?

如何在異步操作完成之前延遲一個承諾? 我正在使用異步和藍鳥庫。 一旦啟動程序,done()函數就會返回一個空的或幾乎為空的'masterlist'對象的錯誤。 為什么在迭代器完成操作之前不等待異步?

// bundler.js

var masterlist = {
   "children": []
 , "keywords": []
 , "mentions": 0
 , "name" : "newsfeed"
 , "size" : 0
}

// initialize() returns a promise with the populated masterlist
exports.initialize = function() {
  return new Promise(function(resolve, reject) {

    // pullBreakingNews() returns a promise with the breaking news articles
    nytimes.pullBreakingNews().then(function(abstracts) {

      async.map(abstracts, iterator, done);

      function iterator(item, callback) {
        alchemyapi.entities('text', item, {}, function(response) {

          // initialize each entity with masterlist
          response.entities.forEach(function(entity) {
            masterlist.children[masterlist.children.length] =
             {
                 "abstract": item
               , "children": []
               , "name": entity.text
               , "size": 0
             };
            masterlist.size += 1;
            masterlist.keywords.push(entity.text);
          });

          callback(masterlist);
        });
      };

      function done(err, results) {
        if (err) {
          console.log("ERROR: ", err);
        } else {
          resolve(results);
        }
      };

    });
  });
};

Firehose.js是調用initializer()的模塊。 我相信firehose首先運行,並在此過程中調用promise。 server.js => firehose.js => bundler.js => nytimes api

// firehose.js
// Compares entities to Twitter stream, counts every match
exports.aggregator = function(callback) {
  bundler.initialize().then(function(masterlist) {

    t.stream('statuses/filter', { track: masterlist.keywords }, function(stream) {

      // read twitter firehose for incoming tweets.
      stream.on('data', function(tweet) {
        var tweetText = tweet.text.toLowerCase();

        // sift through each tweet for presence of entities
        masterlist.children.forEach(function(parentObject) {

          // if the entity exists in the tweet, update counters
          if (tweetText.indexOf(parentObject.name.toLowerCase()) !== -1) {
            parentObject.size += 1;
            masterlist.mentions += 1;
            callback(masterlist);
          }

        });
      });
    });
  });
};

非常感謝您的幫助。

請不要混合回調和承諾,只使用其中任何一個。

// Do this somewhere else, it is only needed once
// it adds promise returning versions of all alchemy methods for you
Promise.promisifyAll(require('alchemy-api').prototype);

exports.initialize = function() {
  return nytimes.pullBreakingNews().map(function(abstract) {
    // Note that it is entitiesAsync that is a promise returning function 
    return alchemyapi.entitiesAsync('text', abstract, {}).then(function(response){
      response.entities.forEach(function(entity) {
            masterlist.children[masterlist.children.length] =
             {
                 "abstract": abstract
               , "children": []
               , "name": entity.text
               , "size": 0
             };
            masterlist.size += 1;
            masterlist.keywords.push(entity.text);
      });
    });
  }).return(masterlist);
};

您的初始化函數也不會檢查它是否已初始化

迭代器的回調接受錯誤作為第一個參數。 如果沒有錯誤,你應該傳遞一個假值(如null)而不是masterlist

function iterator(item, callback) {
    alchemyapi.entities('text', item, {}, function(response) {

      // initialize each entity with masterlist
      response.entities.forEach(function(entity) {
        masterlist.children[masterlist.children.length] =
         {
             "abstract": item
           , "children": []
       , "name": entity.text
       , "size": 0
         };
        masterlist.size += 1;
        masterlist.keywords.push(entity.text);
      });

      callback(null, masterlist);
    });
  };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM