promise with loop and file read in nodejs

后端 未结 2 1087
北荒
北荒 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:16

    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...?

提交回复
热议问题