【问题标题】:JS: How to postpone execution of a functionJS:如何推迟函数的执行
【发布时间】:2018-10-22 17:19:47
【问题描述】:

试图挂载一个 Vue.js 组件,但似乎第二个函数 (eventSelection) 被调用得比预期的要早。我应该怎么做才能使其仅在第一个功能完成后才执行?

...
mounted() {
  this.getAllEvents()
  this.eventSelection()
},

methods: {
  getAllEvents: function () {
    console.log("Cheguei aqui");
    getEvents()
    .then( function (res) {
      console.log("Entrei then")
      this.events = res.data
    }.bind(this))
    .catch( function (err){
      debugger;
      console.error('WeekSimulation, getEvents() ', err)
      this.events = ["Seu chefe o convida para um happy hour com os diretores no final do expediente.  Ao mesmo tempo, você recebe uma mensagem de seu cônjuge lembrando da apresentação no colégio do seu filho. O que você faz?", "Você tem muito trabalho a fazer, porém o tempo com sua família anda escasso. No final do expediente você escolheria jantar com sua família ou fazer hora extra?",
                         "Você acorda de manhã e seu filho não está se sentindo bem. Ao verificar sua agenda, lembra que tem uma reunião com um novo cliente em uma hora. Você leva seu filho ao médico ou vai para a reunião?", 
                         "Ao checar o seu celular durante uma reunião com os diretores de sua organização, nota que recebeu cinco ligações de seu cônjuge. Você continua na reunião, ou pede para atender o telefone?"]
    }.bind(this))
  },

  eventSelection: function() {
    console.log("Funcao de selecao de evento")
    debugger;
    this.selectedEvent = _.shuffle(this.events)[0]
    console.log(this.selectedEvent)
  }      

}
...

【问题讨论】:

  • 努力加分,不过有点臃肿不行吗?
  • 将 this.events 设置为 getEents 的结果,如下所示:this.events=getEents().then(d=>d.data) 和 eventSelection:this.events.then(events=>this.selectedEvent = _.shuffle(this.events)[0])

标签: javascript vuejs2 vue-component


【解决方案1】:

您需要使用promises()。 我无法理解您的代码,抱歉,这是一个通用示例:

first = function(){
    var deferred = new $.Deferred();
    console.log("first running");
    deferred.resolve();  // <----------resolve the deferred
    return deferred.promise();
}

second = function(){
    console.log("second running..sigh..");
}

$(document).ready(function() {

    first().then(second);

});

【讨论】:

  • promise() 答案,OP。听听这家伙的声​​音
  • OP 的代码已经使用了 Promise 或者你不会有 then() 方法
【解决方案2】:

使用简单的回调:

 mounted() {
   this.getAllEvents(this.eventSelection);
 }

 getAllEvents: function (cb) {
    ...
    cb();
 },

  eventSelection: function() {
   ...
  }

【讨论】:

  • getAllEvents 不执行任何回调函数
【解决方案3】:

getAllEvents() 返回 getEvents() 承诺,以便您可以将另一个 then() 链接到它并在 getEvents() 解析后调用 eventSelection()

mounted() {
  this.getAllEvents().then(this.eventSelection)

},

methods: {
  getAllEvents: function () {
   // return the promise
   return getEvents()
    .then( function (res) {
      ....
    }.bind(this))


}

还要确保在catch 中添加return this.events 以解决初始承诺

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    相关资源
    最近更新 更多