簡體   English   中英

Promise.all 在節點 JS 中返回 undefined

[英]Promise.all returning undefined in Node JS

我有一個從第一個 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()似乎沒有返回任何內容,即它返回undefined 嘗試在 function 末尾返回response

async function getFilename(inp_a) {
  const response = ...

  return response;
}

感謝Mat J的評論。 我能夠簡化我的代碼,並且還學會了何時不使用鏈接。

還要感謝 Shadab 的回答,它幫助我知道異步 function 總是返回 promise ,這是默認的 promise 返回而不是實際字符串。 沒有意識到這一點。 (我對 JS 很陌生)

這是我的最終代碼/邏輯有效 -

async function main_function(req,res){
    try{
      const response = await fetch(...)
      const resp = await response.text();
      dirs = ...some logic to extract number of directories...
      const tempPromises = [];

      for (i = 0; i < dirs.length; i++) {
         tempPromises.push(getFilename(i));
      }
      
      Promise.all(tempPromises).then((result_new) => {
         console.log(result_new);
         res.send({ status: "ok" });
       });
    }
    catch(err){
       console.log(err)
       res.send({"status" : "error"})
    }
}

async function getFilename(inp_a) {
  const response = await fetch(...)
  respText = await response.text();
  return("Temp Name"); //
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM