Friday, 26 May 2017

Nested Promises executed in the "wrong" order

i'm trying to open 2 files in a+ mode and then try to read their content and send it back to the user. I had it implemented using nested callbacks but i wanted to try doing it with Promises, thus i wrote the following :

var chain1 = [];  
var c1Promise1 = new Promise(func(res,rej){  
   fs.open('path','a+',func(err,fd){  
     if(err)  
       {rej(err)}  
     else  
       {res(fd)}  
     })  
chain1.push(c1Promise1)  
//Same thing for the second promise, just different path  
Promise.all(chain1).then(fds=>{
    var chain2 = []  
    var c2Promise1 = new Promise(func(res,rej){  
       fs.readFile(fds[0],'utf-8',func(err,data){
          console.log("data1 = " + data)  
          if(err){  
            rej(err)
          }  
          else{  
            res(data)  
          }  
       })  
})
chain2.push(c2Promise1)
//Same thing for c2Promise2 but different fd (fds[1]) and .log("data2 = " + data)
Promise.all(chain2).then(data=>{
       console.log("data3 and 4 = " + data[0] + ' ' + data[1])
   },err=>next(err))
},err=>next(err))  

On console i get:  
"data3 and 4" = undefined undefined    
"data1 = " actual data in the file  
"data2 = " actual data in the file.   

Am i missing something?Isnt this supposed to behave like, data1, data2 and only then data 3 and 4!? Thanks for help



via Filippo Bosco

No comments:

Post a Comment