等待if语句VUE内部的promise中的数据

时间:2018-09-06 06:37:12

标签: javascript vue.js promise vue-component

我有此登录功能,我想在其中向会话提供一些以后可以使用的数据。

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

这是我的承诺:

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是保留字

promise

如您所见,在尝试将我加入会话后,它给了我结果。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用异步处理程序.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')
    }
  })
 }