gpt4 book ai didi

javascript - promise 在nodejs中读取循环和文件

转载 作者:搜寻专家 更新时间:2023-11-01 00:32:08 25 4
gpt4 key购买 nike

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

问题..

  1. loop中的内容应该传递给一个一个执行。
  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

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

上传多个同名文件。

..

最终预期的 promise 是

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

- 保存到数据库。

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

问候模因

最佳答案

您正在寻找的技术是 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
}));
});
});

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

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

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

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

关于javascript - promise 在nodejs中读取循环和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27468188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com