promise with loop and file read in nodejs

后端 未结 2 1089
北荒
北荒 2021-01-21 22:46

I looked at lot of example but couldn\'t achieve it..so need help..

Problem..

  1. the content from loop should be passed to execute one by one
2条回答
  •  礼貌的吻别
    2021-01-21 23:29

    The technique you're looking for is thenable chaining

    var p= Q();
    Object.keys(files).forEach(function(key){
      p = p.then(function(){ // chain the next one
        return Q.nfcall(fs.readFile, files[key].path, "binary", i). // readfile
          then(function (content) { // process content and save
            files.filename =  files[key].name;
            files.path = files[key].path;
            files.content_type = files[key].type;
            files.size = files[key].size;
            console.log(files.filename);
            files.content = binaryToBase64(content);
            return Q.npost(art.save, art); // wait for save, update as needed
        }));
      });
    });
    

    Basically, we tell each operation to happen after the previous one has finished by chaining them and returning which causes a wait on the asynchronous value.

    As a byproduct you can later use

    p.then(function(last){
        // all done, access last here
    });
    

    The handler will run when all the promises are done.

提交回复
热议问题