javascript - looping promises in nodejs -


i learning promises in nodejs, below example code. output of below code test - 1 test - 2 test - 3 test - 4

var q = require('q'); var promise = q.when('test');  promise.then( function(val) { console.log(val + '-' + '1'); });  promise.then( function(val) {  console.log(val + '-' + '2'); });  promise.then( function(val) {  console.log(val + '-' + '3'); });  promise.then( function(val) { console.log(val + '-' + '4'); }); 

i know how can write same code using loop.

this isn't specific promises. if you're creating callbacks in loop, you'll need closure scope, other it's quite standard.

however, simplest way specific case use single callback only, attached same promise anyway , receive same value. use

require('q').when('test').then(function(val) {     (var i=1; i<=4; i++) {         console.log(val + '-' + i);     } }); 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -