在Vue组件中链接不同的API调用,包括带有for循环的API调用

我试图了解如何在' notes 'Vue组件中链接两个不同的API调用,包括一个带for循环的调用。我对诺言非常有基本的经验,我正在寻求改进。

我正在进行第一个API调用以获取所有注释,并使用Vuex突变将它们推入数组。在第一次API调用期间,我还将不同用户的电子邮件映射到一个对象。

使用此映射对象,我正在for循环内进行第二次API调用,以获取所有用户的头像。

第一个API调用如下所示:

getallNotesAPI(entity) {
  noteService.getNotes(entity)
    .then((response) => {

      if (response.data.length === '0') {
        // Set hasData to false if the response is 0
        this.hasData = false;
      } else {
        // Push data into the note array using a store mutation
        this.setallNotes(response.data);
      }

      // Mapping all users emails into 'userEmails'
      this.userEmails = [...new Set(response.data.map(x => x.userEmail))];

      // Calling my second API call here to get all the avatars associated with these emails
      for (let i = 0; i < this.userEmails.length; i++) {
        this.getavatarAPI(this.userEmails[i])
      }
    })
    .catch((error) => {
      console.log(error);
    })
    .finally(() => {
      this.endLoader('notes');
    });
},

this.getavatarAPI 是第二个API调用,如下所示:

getavatarAPI(login) {
  userService.getavatar(login)
    .then((response) => {

      let newAvatar = {
        userEmail: login,picture: response.data.picture
      };
      // Push the response into a userAvatar Object using a store mutation
      this.setUserAvatar(newAvatar);
    }).catch((error) => {
      console.log(error)
  })
},

我尝试使用async / await,但无法弄清楚如何将其绑定到async函数内部(this.getavatarAPI(this.userEmails))未定义,然后尝试使用倍数进行链接,但无法t弄清楚如何:在完成所有这些API调用后,获取所有笔记,然后所有化身,然后结束“ note”加载器。

如果你们中的任何人可以给我一些指示或答案的开头,那将是不胜感激的!

sgdtiancai 回答:在Vue组件中链接不同的API调用,包括带有for循环的API调用

首先,尽管与您的问题无关,但在不必要时避免for循环:

您需要i索引吗?

  for (let i = 0; i < this.userEmails.length; i++) {
    this.getAvatarAPI(this.userEmails[i])
  }

不。您需要userMail。然后

  this.userEmails.forEach(userMail => {
    this.getAvatarAPI(userEmail)
  })

现在,要同步Promise,您需要返回 Promise(让我们不再谈论异步)

  1. 使getAvatarAPI返回承诺
getAvatarAPI(login) {
  return userService.getAvatar(login).then(blabla) // notice the return here
  1. 获取getAvatar API的承诺
  let promises = this.userEmails.map(userMail => {
    return getAvatarAPI(userEmail)
  })
  1. 在所有诺言兑现后返回
  let promises = this.userEmails.map(userMail => {
    return getAvatarAPI(userEmail)
  })
  return Promise.all(promises)

在带有异步/等待的旁注

如果您使用它,就不再被迫再写return了,但是您需要写async / await

基本思想保持不变。指定async关键字表示您的函数将返回类似promise的消息。

例如

  async function p () {
    return 5
  }

  p.then(x => console.log(x)) // does print 5 even though we didn't explicitely write return Promise.resolve(5)

现在,您必须确保,在调用异步函数时要等待它:

  getAvatarAPI: async login => {
    return userService.getAvatar(login).then(blabla)
  }

  // DO NOT do it
  this.userEmails.forEach(userMail => {
    return await this.getAvatarAPI(userEmail)
  })

在上面的forEach循环中,您将以顺序进行getAvatarAPI调用,因为只要getAvatarAPI仍未解决,则等待“停止”迭代。

正确的方法是

  getAllNotesAPI: async entity => {
    try { // notice the necesary try-catch block
      const response = await noteService.getNotes(entity)
      blabla
      let promises = this.userEmails.map(userMail => {
        return this.getA...
      })
      let result = await Promise.all(promises)
      // eventually return result,or simply await Promise... without lefthand-side assignment
    } catch (error) {
      console.log(error);
    }
    console.log(this.end('loader'))
  }
本文链接:https://www.f2er.com/3050280.html

大家都在问