【发布时间】:2021-06-24 00:41:57
【问题描述】:
我有一个从第一个 API 获取目录名称的代码。对于每个目录,需要从第二个 API 获取文件名。我在我的 Node JS 代码中使用了类似的东西 -
async function main_function(req, res) {
const response = await fetch(...)
.then((response) => {
if (response.ok) {
return response.text();
} else {
return "";
}
})
.then((data) => {
dirs = ...some logic to extract number of directories...
const tempPromises = [];
for (i = 0; i < dirs.length; i++) {
tempPromises.push(getFilename(i));
}
console.log(tempPromises); // Prints [ Promise { <pending> } ]
Promise.all(tempPromises).then((result_new) => {
console.log(result_new); // This prints "undefined"
res.send({ status: "ok" });
});
});
}
async function getFilename(inp_a) {
const response = await fetch(...)
.then((response) => {
if (response.ok) {
return response.text();
} else {
return "";
}
})
.then((data) => {
return new Promise((resolve) => {
resolve("Temp Name");
});
});
}
我在这里错过了什么?
【问题讨论】:
-
您正在混合等待和链接以在
getFileName内部造成混乱。您不需要在其中使用带有then的链接。只需在 await 行下方将其编写为普通代码并返回即可。这就是使用 await 的意义所在。 -
"这会打印 "undefined"" - 我不认为它可以。
Promise.all创建一个始终通过数组实现的承诺。