承诺在 NodeJS 中循环和文件读取

promise with loop and file read in nodejs

本文关键字:文件 读取 循环 NodeJS 承诺      更新时间:2023-09-26

我看了很多例子,但无法实现。所以需要帮助..

问题。。

  1. 来自循环的内容应逐个传递以执行。
  2. 每个循环迭代都包含一个文件读取和数据库保存操作,以及一些需要分配的其他对象属性。

我在这里创建了示例..

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

如何运行:

接口:http://web-91b5a8f5-67af-4ffd-9a32-54a50b10fce3.runnable.com/api/upload

方法 : 开机自检

内容类型:多部分/表单数据

上传多个带有名称的文件。

..

最终的预期承诺是

files.name = "name of file"
files.content
files.content-type
files.size

- 保存到数据库。

目前我从文件中获取不同的内容。但其他文件内容未填充且未定义。

问候莫妍

您正在寻找的技术是可链接

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
    }));
  });
});

基本上,我们通过链接它们并return ing 来告诉每个操作在前一个操作完成后发生,这会导致对异步值的等待。

作为副产品,您可以稍后使用

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

处理程序将在完成所有承诺后运行。

我已经用Q.all更新了代码,因为提到的p.then只会执行一次。

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);
    });
});

问题是如果我有猫鼬模型文件并想保存...,如何使用 q.npost?