繁体   English   中英

在遍历对象数组时分配 axios 响应

[英]Assigning axios response whilst iterating through array of objects

我希望为 Axios 调用中的对象数组分配一个值。 我不知道如何将值分配给新数组。 以下是我到目前为止的代码。

谢谢你。

app.get('/matchedusers', (req, res) => {
  plexClient.getAllUsers().then(plexUsers => {
    axios.get('https://tautulli.link/api/v2?apikey=API-KEY&cmd=get_users_table&length=150')
      .then((tautulliUser) => {
        let tautulliUsers = tautulliUser.data.response.data.data
        let matchedUsers = []
        let timedUsers = []
        

        // Doing a check to see if tautulli user is also a plex user.
        tautulliUsers.forEach((tautulliUser) => {
          plexUsers.forEach((plexUser) => {
            if(tautulliUser.username == plexUser.username || tautulliUser.username == plexUser.email){
              matchedUsers.push({id: plexUser.id, username: plexUser.username, email: plexUser.email})
            }
          })
        })


        matchedUsers.forEach((user) => {
          axios.get(`https://tautulli.link/api/v2?apikey=API-KEY&cmd=get_user_watch_time_stats&user_id=${user.user_id}&query_days=7`)
            .then((watchTime) => {
              // I want to add the matched user to timedUsers and add the watchTime response. Something like "timedUsers.push({...user, response: response})"
              // This is the part that I can't figure out.
            })
        })


        
        // Use the timedUsers array to display the results.
        console.log(timedUsers)
        res.json(timedUsers)
      })
  })
})

使用Promise.all(arrayOfPromises).then(...)等待一系列承诺完成。

如果您曾经在 Javascript function 中引入异步代码,您总是需要等待异步响应完成,因此您只能访问下一个.then()中的数组。

将整个 function 更改为使用async / await语法可以使它更易于使用。

Promise.all(matchedUsers.map((user) =>
  axios.get(`https://tautulli.link/api/v2?apikey=API-KEY&cmd=get_user_watch_time_stats&user_id=${user.user_id}&query_days=7`)
    .then((response) => ({ ...user, response }))
).then(res => {
  timedUsers = res;
}

Note the matchedUsers.map((user) => axios.get... syntax, which doesn't put a curly brace around the function body. This is an implicit Javascript return, so the map will return an array of the axios get承诺。

(response) => ({...user, response })相同,这是从 function 显式返回的 object。 您必须将 object 包含在( )中,以表示它是隐式的 object 返回。

您应该使用Promise.all ,我还将您的路由转换为 async/await 语法,因为它更易于阅读和使用。 不建议在循环中等待,最好将所有承诺推送到一个数组,然后使用Promise.all等待全部。

 app.get('/matchedusers', async(req, res) => { const allUsers = await plexClient.getAllUsers(); const tautulliUser = await axios.get('https://tautulli.link/api/v2?apikey=API-KEY&cmd=get_users_table&length=150'); let tautulliUsers = tautulliUser.data.response.data.data let matchedUsers = [] let timedUsers = [] tautulliUsers.forEach((tautulliUser) => { plexUsers.forEach((plexUser) => { if (tautulliUser.username == plexUser.username || tautulliUser.username == plexUser.email) { matchedUsers.push({ id: plexUser.id, username: plexUser.username, email: plexUser.email }) } }) }) matchedUsers.forEach((user) => { const response = axios.get(`https://tautulli.link/api/v2?apikey=API-KEY&cmd=get_user_watch_time_stats&user_id=${user.user_id}&query_days=7`); timedUsers.push({...user, response }); }) const final = await Promise.all(timedUsers); console.log(final) res.json(final) })

我建议您使用async/await语法,并使用Promise.allmap先解决请求承诺,然后将它们添加到timedUsers数组。

 app.get("/matchedusers", async (req, res) => { const plexUsers = await plexClient.getAllUsers(); const tautulliUser = await axios.get( "https://tautulli.link/api/v2?apikey=API-KEY&cmd=get_users_table&length=150" ); let tautulliUsers = tautulliUser.data.response.data.data; let matchedUsers = []; let timedUsers = []; // Doing a check to see if tautulli user is also a plex user. tautulliUsers.forEach((tautulliUser) => { plexUsers.forEach((plexUser) => { if ( tautulliUser.username == plexUser.username || tautulliUser.username == plexUser.email ) { matchedUsers.push({ id: plexUser.id, username: plexUser.username, email: plexUser.email, }); } }); }); // I want to add the matched user to timedUsers and add the watchTime response. Something like "timedUsers.push({...user, response: response})" // This is the part that I can't figure out. timedUsers = await Promise.all( matchedUsers.map(async (user) => { const response = await axios.get( `https://tautulli.link/api/v2?apikey=API-KEY&cmd=get_user_watch_time_stats&user_id=${user.user_id}&query_days=7` ); return {...user, response } }) ); // Use the timedUsers array to display the results. console.log(timedUsers); res.json(timedUsers); });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM