javascript - Promise inside a settimeout -


i'm trying run promises in 1 second delay each other, api server i'm working has 1 request per second limit.

here code currently

var delay = 0; return categories.reduce(function(promise, category) {   var id = settimeout(function() {     promise.then(function() {        return client.itemsearch({         searchindex: configuration.searchindex,         categoryid: category.id,         keywords: currentkeyword        }).then(function(results) {         var title = results[0].title;         var cat = category.name;         var price = results[0].price;          return db.insertproduct(title, cat, price);       });     }).catch(function(err) {       console.log("error", err);     });    }, delay * 1000);    delay += 1; }, promise.resolve()); 

for every time loops over, increases delay one, next item start delay of 1 second.

so if first item, 0*1 = 0, 1*1 = 1, 2*1 = 2... on

for reason, doesnt work, without settimeout works perfectly.

as far can tell, there shouldnt problem starting promise after delay, unless maybe has variables not having right value after when delay finished. if that's case, how can fix that, maybe pass on variables?

i appreciate every can get.

using async.eachseries, can process each of these in series , execute asynchronous callback 1 second after each request finishes:

async.eachseries(categories, function(category, callback) {   client.itemsearch({     searchindex: configuration.searchindex,     categoryid: category.id,     keywords: currentkeyword   }).then(function(results) {     // don't need wait after database here, after request     settimeout(callback, 1000);      var title = results[0].title;     var cat = category.name;     var price = results[0].price;      db.insertproduct(title, cat, price);   }).catch(callback); }, function(err) {   if (err) {     console.log('error', err);   } }); 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

android - Keyboard hides my half of edit-text and button below it even in scroll view -