Nodejs Synchronous For each loop

后端 未结 6 1571
刺人心
刺人心 2020-12-28 15:51

I want to do a for each loop but have it run synchronously. Each iteration of the loop will do an http.get call and that will return json for it to insert the values into a

6条回答
  •  青春惊慌失措
    2020-12-28 16:23

    To loop and synchronously chain asynchronous actions, the cleanest solution is probably to use a promise library (promises are being introduced in ES6, this is the way to go).

    Using Bluebird, this could be

    Var p = Promise.resolve();
    forEach(sets, function(item, index, arr) {
        p.then(new Promise(function(resolve, reject) {
             http.get(theUrl, function(res) {
             ....
             res.on('end', function() {
                  ...
                  resolve();
             }
        }));
    });
    p.then(function(){
       // all tasks launched in the loop are finished
    });
    

提交回复
热议问题