for promise的for循环在nodejs中无法正常工作

时间:2014-06-17 07:13:16

标签: javascript node.js postgresql

我是nodejs的新手,我试图在for循环中使用promises,其中我首先获得postgres序列的下一个值,然后将其值重置为

for(var i=0;i<3;i++){
    getNextVal().then( function(result) {
        var nextVal = result.nextval;
        console.log("next value :"+nextVal);
        setSeqVal(nextVal).then( function(result) {
           console.log("reset value :"+result.curValOfSeq);
        });
    });
}

function getNextVal(){
    var promise = new Promise (function(resolve, reject) {
        pg.connect(conString, function(err, client, done){
            if(err) {
                console.log ('error fetching client from pool ' + err);
                reject (err);
            }
            client.query("select nextval('test_seq')", function(err, result) {
                done();
                    if(err) {
                        console.log('error running query', err);
                        reject (err);
                    }
                    if (result.rows) {
                        resolve({'nextval' : result.rows[0].nextval});
                    }
                    else {
                        console.log('Could not get next value');
                    }
            });
        });
    });
    return promise;
};

function setSeqVal (curVal){
    var promise = new Promise (function(resolve, reject) {
        pg.connect(conString, function(err, client, done){
            if(err) {
                console.log ('error fetching client from pool ' + err);
                reject (err);
            }
            client.query("ALTER SEQUENCE test_seq RESTART WITH "+curVal, function(err, result) {
                done();
                if(err) {
                    console.log('error running query', err);
                    reject (err);
                }
                resolve({'curValOfSeq' : curVal});
            });
        });
    });
    return promise; 
};

输出结果如下:

next value :1
next value :2
next value :3
reset value :1
reset value :2
reset value :3

我希望输出如下:

next value :1
reset value :1
next value :2
reset value :2
next value :3
reset value :3 

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

您希望顺序工作似乎不是并行工作。

您可以尝试这样的事情:

var LIMIT = 3;
var doTheNext = function(index) {
    if(index < LIMIT) {
        getNextVal().then( function(result) {
                var nextVal = result.nextval;
                console.log("next value :"+nextVal);
                setSeqVal(nextVal).then( function(result) {
                   console.log("reset value :"+result.curValOfSeq);
                   doTheNext(++index);
                });
            });
    }
};

doTheNext(0);