簡體   English   中英

承諾與forEach

[英]promise.all with forEach

我已經編輯了問題。 更改為語法錯誤,但仍然無法正常工作。 我正在使用github api獲取用戶列表,然后為每個用戶獲取他的存儲庫。 我的想法是獲取所有存儲庫(完成后),然后將allRepos數組放入用戶對象中,然后返回用戶對象以便渲染它。 我已經通過Promise.all內部的foreach循環完成了此操作。 我知道我沒有正確使用它,因為在Promise.all之后不能使用.then()。 是否可以按照我需要的方式使用Promise。,還是必須事先定義要放入的數組? 幫助將不勝感激。

 function onGetUsers() { // var prmUsers=getUsers() getUsers() .then(getrepos) .then(data=> console.log(data))//here i want to render the object } function getrepos(users){ var usersObj={ users: users, } var allRepos = [] Promise.all(users.forEach(user => { var currUser = axios.get(user.repos_url) .then(data => allRepos.push(data)); return currUser; })).then('here i want to put allRepos in the usersObj') return usersObj } function getUsers() { var prmRes = axios.get('https://api.github.com/users'); var prmUsers = prmRes.then(res => { return res.data; }); return prmUsers; } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/index.css"> <title>Github Users</title> </head> <body> <button onclick="onGetUsers()">Get Users</button> <script src="lib/axios.js"></script> <script src="js/index.js"></script> </body> </html> 

function getrepos(users){
   let p = Promise.resolve(true);
    users.map(user => {
      p = p.then(() => axios.get(user.repos_url).then(userRepos => user.repos = userRepos));
    });
    return p.then(() => users);

}

使用此方法,您將獲得users對象,其中每個用戶都將具有由其回購構成的repos屬性。 您只需要用此方法替換一種方法即可。 在最后的地方,您可以遍歷它們,並將所有存儲庫也合並為一個陣列。

單擊按鈕,等待請求完成

 function onGetUsers() { // var prmUsers=getUsers() getUsers() .then(getrepos) .then(data=> { console.log(JSON.stringify(data)); }) } function getrepos(users){ const userPromises = users.map(user => { return axios.get(user.repos_url).then(userRepos => user.repos = userRepos); }); return Promise.all(userPromises) } function getUsers() { var prmRes = axios.get('https://api.github.com/users'); var prmUsers = prmRes.then(res => { return res.data; }); return prmUsers; } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/index.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script> <script src="js/index.js"></script> <title>Github Users</title> </head> <body> <button onclick="onGetUsers()">Get Users</button> </body> </html> 

暫無
暫無

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

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