promise with loop and file read in nodejs

旧巷老猫 提交于 2019-12-02 00:46:24

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.

I have updated the code with Q.all as the mentioned p.then will execute only once.

http://runnable.com/VI1efZDJvlQ75mlW/api-promise-loop-for-node-js-and-hello-world

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

        Q.all(promises);
    });
});

the question is how to use q.npost if i have mongoose model files and want to save...?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!