在nodejs中使用循环和文件读取的承诺 [英] promise with loop and file read in nodejs

查看:71
本文介绍了在nodejs中使用循环和文件读取的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

问题..

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

我在这里创建了示例..

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

如何运行:

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

方法:POST

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

content-type : multipart/form-data

上传多个有名称的文件.

upload more than one file with name.

...

最终的预期承诺是

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

- 保存到数据库.

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

currently i am getting different content from file..but other files content are not filled and is undefined.

问候莫伊恩

推荐答案

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

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

基本上,我们告诉每个操作在前一个操作完成后发生,方法是将它们链接起来并returning,这会导致对异步值的等待.

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.

这篇关于在nodejs中使用循环和文件读取的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆