我看了很多例子但无法实现它..所以需要帮助..
问题..
- 循环中的内容应该被传递来逐一执行。
- 每次循环迭代都包含文件读取和数据库保存操作以及需要分配的其他一些对象属性。
我在这里创建了示例..
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
内容类型:多部分/表单数据
上传多个同名文件。
..
最终的预期 promise 是
files.name = "name of file"
files.content
files.content-type
files.size
-保存到数据库。
目前我从文件中获取不同的内容..但其他文件内容未填充且未定义。
问候 莫伊恩
最佳答案
您正在寻找的技术是 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
}));
});
});
基本上,我们通过链接每个操作并返回来告诉每个操作在前一个操作完成后发生,这会导致异步值等待。
作为副产品,您可以稍后使用
p.then(function(last){
// all done, access last here
});
处理程序将在所有 promise 完成后运行。
关于javascript - 在 Node.js 中使用循环和文件读取进行 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27468188/