簡體   English   中英

JS,映射數組時在 Axios 中使用 Async Await function

[英]JS, use of Async Await function in Axios when mapping over an array

function 旨在循環數組並將數組中的每個值發布到數據庫。 如果我使用異步等待 function,則會出現錯誤。

錯誤:不能在異步 function 之外使用關鍵字“等待”

 const myfunction = async () => {
    [1,2,3].map((item) => {
      
      const endpoint = "/api/";

      await apiService(endpoint, "POST", item)
        .then((r) => console.log(r))
        
    });
  };

apiservice function 使用瀏覽器獲取 function 和存儲的 cookie

這可能與以下問題Using async await when mapping over an arrays values重復,但我不明白。

原因是await不會直接發生在您的async function 中,而是在傳遞給.map的 function 中發生(這不是async的)。

此外, .map在這里被濫用,因為你沒有在回調中返回任何內容,也沒有使用.map返回的數組。

只需使用for循環:

const myfunction = async () => {
    for (let item of [1,2,3]) {      
        const endpoint = "/api/";
        await apiService(endpoint, "POST", item)
            .then((r) => console.log(r))
    }
}

此外,使用then在這里是一種反模式,因為await實際上是為了避免使用它。 所以最好像這樣編碼:

const myfunction = async () => {
    for (let item of [1,2,3]) {      
        const endpoint = "/api/";
        let r = await apiService(endpoint, "POST", item)
        console.log(r);
    }
}
const myfunction =  () => {
    [1,2,3].map( async(item) => { // async should be here
      
      const endpoint = "/api/";

      await apiService(endpoint, "POST", item)
        .then((r) => console.log(r))
        
    });
  };

這應該工作

 const myfunction = () => {
    [1,2,3].map(async (item) => {
      
      const endpoint = "/api/";

      await apiService(endpoint, "POST", item)
        .then((r) => console.log(r))
        
    });
  };

暫無
暫無

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

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