【问题标题】:how to make vue firebase call asynchronous如何使vue firebase调用异步
【发布时间】:2021-11-05 05:33:52
【问题描述】:

我正在使用亚马逊机械土耳其人来雇佣一些工人。我正在使用带有firebase的vue。在firebase中,我有命中(mturk),我想在mturk iframe中提交表单时关闭命中。问题是有时它会关闭命中,有时却不是。

public async submitAssignment() {
var urlParams = new URLSearchParams(window.location.search)
if (urlParams.has('assignment_id')) {
  this.host = urlParams.get('host')
  this.assignmentId = urlParams.get('assignment_id')
  this.workerId = urlParams.get('workerId')
  this.hitId = urlParams.get('hitId')

  const oFormObject = document.forms['mturkForm']
  oFormObject.action = this.host
  oFormObject.elements['assignmentId'].value = this.assignmentId
  oFormObject.elements['workerId'].value = this.workerId
  oFormObject.elements['hitId'].value = this.hitId

// form is not waiting for this before submitting the form
  await this.$store.dispatch('hits/closeHit', {
    hitId: this.hitId,
    workerId: this.workerId
  })

  oFormObject.submit()
}

}

Vuex 操作

const actions = {
  async closeHit({}, payload: any) {
    await db.hits
      .setDone(payload)
      .then()
      .catch((error) => {
        console.log(error)
      })
  }
}

hits.ts

  async setDone(payload: any) {
    try {
      return firestore.db
        .collection(collectionNamespace)
        .doc(payload.hitId)
        .update({
          open: false,
          workerId: payload.workerId
        })
    } catch (error) {
      console.error('Error updating document: ', error)
    }
  }

【问题讨论】:

  • 能否显示对应的Vuex动作的代码(store.dispatch方法触发的那个)
  • 我添加了相关代码sn-ps

标签: javascript firebase vue.js asynchronous amazon


【解决方案1】:

我不确定它是否会导致您当前的问题,但这段代码似乎是一个反模式:

const actions = {
  async closeHit({}, payload: any) {
    await db.hits
      .setDone(payload)
      .then()
      .catch((error) => {
        console.log(error)
      })
  }
}

您应该使用 either then await,而不是同时使用。现在你的then 没有做任何事情,但可能会破坏await

更简单,更可能是正确的:

const actions = {
  async closeHit({}, payload: any) {
    await db.hits
      .setDone(payload)
  }
}

【讨论】:

  • 我删除了那部分,但这不是修复。
【解决方案2】:

您可以使用以下语法

await this.$store.dispatch('hits/closeHit', {
    hitId: this.hitId,
    workerId: this.workerId
  }).then(() => { 
 oFormObject.submit()
 })

【讨论】:

  • 但这不是一回事吗?
  • javascript 是非阻塞的,它不会等待上层函数完成。在 then(() => {}) 之后将在您的情况下成功执行相同的函数后调用 'hits/closeHit'
猜你喜欢
  • 2022-06-27
  • 2020-10-23
  • 1970-01-01
  • 2019-11-15
  • 2018-07-07
  • 2021-02-11
  • 1970-01-01
  • 2023-03-25
  • 2018-03-15
相关资源
最近更新 更多