我是Javascript / Nodejs的初学者。
我想读取一个文件夹,然后每一个调用一个函数与等待.
我有一个文件夹,在那个文件夹里我有图像。使用readdir,我可以获得所有带有扩展的文件夹图像。
使用该代码,我读取文件夹并拆分ImageName和.png,因此我只有没有.png的ImageName。
如果有更好的解决方案,就开始行动吧。
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
const split = file.split('.');
.....split[0]
});
});如果我在readdir中添加以下代码
storeAsset();storeAsset代码
async function storeAsset() {
const client = new NFTStorage({ token: NFT_STORAGE_API_KEY })
const metadata = await client.store({
name: 'ExampleNFT',
description: 'My ExampleNFT is an awesome artwork!',
image: new File(
[await fs.promises.readFile('assets/Test.png')],
'MyExampleNFT.png',
{ type: 'image/png' }
),
})
console.log("Metadata stored on Filecoin and IPFS with URL:", metadata.url)
}函数storeAsset()运行时没有问题,但它没有等待完成StoreAsset,然后每个函数都完成。
如果我添加等待,forEach循环等待完成每个文件.;
await storeAsset();我收到这样的信息:
await storeAsset();
^^^^^
SyntaxError: Unexpected reserved word
←[90m at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:115:18)←[39m
←[90m at ESMLoader.moduleProvider (node:internal/modules/esm/loader:289:14)←[39m
←[90m at async link (node:internal/modules/esm/module_job:70:21)←[39m那么,我如何修改readdir函数,通过等待每个函数调用等待完成,然后再等待下一个函数的重新配置来修改readdir函数?
谢谢你的帮助
编辑:
我现在有了这个:
fs.readdir(testFolder, (err, files) => {
files.forEach(async file => {
const split = file.split('.');
//
await storeAsset();
//
console.log(split[0]);
// process.exit(1);
});
});但有点不对劲..。
Metadata stored on Filecoin and IPFS with URL: ipfs://xxx/metadata.json
4
Metadata stored on Filecoin and IPFS with URL: ipfs://xxx/metadata.json
5
Metadata stored on Filecoin and IPFS with URL: ipfs://xxx/metadata.json
1
Metadata stored on Filecoin and IPFS with URL: ipfs://xxx/metadata.json
3
Metadata stored on Filecoin and IPFS with URL: ipfs://xxx/metadata.json
2我需要:1图片>上传等待返回答案,然后2图片等等,而不是每次上传同时开始,然后上传是混合的,而不是1,2,3,4,5.
发布于 2022-03-29 11:52:05
这是一个通用示例,演示如何与readdir和循环一起使用异步代码。
const fs = require("fs")
function pr(f) {
return new Promise((resolve, _reject) => {
setTimeout(function () {
resolve("got file " + f)
}, 500)
})
}
const pth = __dirname; // whatever directory path with something in it...
fs.readdir(pth, async (err, files) => {
// Don't use a forEach syntax as it doesn't support asynchronous code,
// it would not throw an error, but the promises won't be
// resolved inside the loop with forEach.
for (const f of files) {
const msg = await pr(f);
console.log(msg)
}
})下面是一个与您的情况相对应的示例(它不完全了解在何处调用存储资产以及如何使用文件迭代器,但应该说明这一点)
fs.readdir(testFolder, async (err, files) => {
// ...
for (const file in files) {
await storeAsset();
}
// ...
});发布于 2022-03-29 10:16:53
要让迭代等待上一次迭代,而前一次迭代正在运行异步,您可以使用简单的For循环等待它。
像forEach这样的数组方法没有允许它们在进入下一个迭代之前等待异步操作完成的机制。
最后,获得SyntaxError: Unexpected reserved word的原因是forEach函数必须是异步函数,尽管这不能解决您在这里试图解决的问题。
const run = async () => {
for (const x of list) {
await do(x)
}
}
run()https://stackoverflow.com/questions/71660171
复制相似问题