2

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

问题..

  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

方法:POST

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

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

..

最终的预期承诺是

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

- 保存到数据库。

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

问候莫伊恩

4

2 回答 2

4

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

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

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

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

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

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

于 2014-12-14T12:01:35.140 回答
0

我已经用 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 如果我有猫鼬模型文件并想保存...?

于 2014-12-14T16:51:13.750 回答