承诺在 NodeJS 中循环和文件读取
promise with loop and file read in nodejs
我看了很多例子,但无法实现。所以需要帮助..
问题。。
- 来自循环的内容应逐个传递以执行。
- 每个循环迭代都包含一个文件读取和数据库保存操作,以及一些需要分配的其他对象属性。
我在这里创建了示例..
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?
相关文章:
- Javascript:检测文件读取器中是否有图像
- 从多个文件中推送文本的函数(使用html5文件读取器上传)返回数组
- 从d3.js中的文件读取json数据不起作用
- Javascript文件读取器
- 从外部javascript文件读取var并将其转换为php变量
- 在jQuery/JS中将文件读取为字符串
- Chrome应用程序:从服务器上的文件读取和写入数据
- 文件读取器无法在chrome和IE中工作
- 将节点.js对象设置为从文件读取的数据
- Django从通过网站上传的文件读取
- 在文件读取器中追加的订单问题
- 从 JavaScript 中的本地 JSON 文件读取时出错
- 是否有可能使用三个.js文件读取STEP文件
- 将文件读取到 blob 并以 JavaScript 格式显示
- 文件读取器和 Blob 的关闭编译器警告 - 无法修复它
- 使用 knex 从文件读取并插入数据库结束错误
- Corodva 文件读取执行成功和失败回调
- 文件读取器 JS 抛出对象正忙于读取 blob
- 承诺在 NodeJS 中循环和文件读取
- 无法弄清楚 $.get 上的回调以将文本文件读取到数组中