bluebirdjs promises wrapped inside a for loop

前端 未结 2 1429
别那么骄傲
别那么骄傲 2021-01-25 04:25

I have a bunch of functions used to provide data to my service. I want to loop through each of them and stop as soon as one of them returns the desired result. If the first one

2条回答
  •  一个人的身影
    2021-01-25 04:46

    if promises are not a hard constraint caolan/async#eachSeries or similar might help. Something like...

    // var Promise = require(?)
    // var async = require("async")
    handleData: asyncProviderFinder
    
    ...
    
    function asyncProviderFinder(address){
      var self = this;
      return new Promise(function(resolve, reject){
        async.eachSeries(
          self.listAllAvailableProviders, 
          function iterate(provider, next){
            var handler = provider;
            new handler().getData(address)
            .then( function(value){
              Logger.info(value);
              next("abort"); // callback any error to abort future iterations
              return resolve(value);
            })
            .catch( function (err){
              Logger.error(err);
              next();
            });
          },
          function callback(err, firstProvider){
            if ((firstProvider === undefined) && !err ){ reject(""); }
          }
        );
      });
    }
    

提交回复
热议问题