【问题标题】:Await data from promise inside if statement VUE在 if 语句 VUE 中等待来自 Promise 的数据
【发布时间】:2018-09-06 06:37:11
【问题描述】:

我有这个登录功能,我想在里面给我的会话一些我以后可以使用的数据。

问题是当我想将数据推送到我的会话时,我从一个承诺中得到它试图在我从我的承诺中得到结果之前将数据放入。

这是我的承诺:

async setData (storeId) {
      var getData = new Promise(function (resolve, reject) {
        let data = Functions.getScore('day', storeId)
        data.then(function (result) {
          resolve(result)
        })
      })
      getData.then(function (result) {
        console.log(result)
        return result
      })

这是我的登录功能

login () {
      axios.post('API', {
        username: this.username,
        password: this.password,
        'condition': 'dashboard'
      }).then(response => {
        if (!response.data.Error) {
          var storeId = response.data.accessId
          this.$session.start()
          this.account = response.data
          // here do i want to store the data.
          this.$session.set('store', this.setData(storeId)) 
          this.$session.set('user', response.data)
          console.log(this.$session.getAll())
          //i will get my result here AFTER it should have filled the session 
        } else {
          alert('something went wrong')
        }
      })
     }

我尝试将 await 放入我的 if 函数中,但它说 await 是保留字

正如您在此处看到的,它在我尝试将 i 放入会话后给了我结果。

提前致谢!

【问题讨论】:

    标签: javascript vue.js promise vue-component


    【解决方案1】:

    您可以使用异步处理程序.then(async response => {})

    login () {
      axios.post('API', {
        username: this.username,
        password: this.password,
        'condition': 'dashboard'
      }).then(async response => {
        if (!response.data.Error) {
          var storeId = response.data.accessId
          this.$session.start()
          this.account = response.data
          // here do i want to store the data.
          const storeData = await this.setData(storeId)
          this.$session.set('store', storeData) 
          this.$session.set('user', response.data)
          console.log(this.$session.getAll())
          //i will get my result here AFTER it should have filled the session 
        } else {
          alert('something went wrong')
        }
      })
     }
    

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 1970-01-01
      • 2020-05-08
      • 2023-03-13
      • 2021-03-02
      • 1970-01-01
      • 2018-07-08
      • 2023-01-20
      • 1970-01-01
      相关资源
      最近更新 更多