【问题标题】:Synchronous run-time with different function time execution [duplicate]具有不同功能时间执行的同步运行时[重复]
【发布时间】:2018-04-02 04:58:03
【问题描述】:

我正在尝试同步运行 2 个函数。第一个函数的执行速度比第二个函数慢很多。我需要它从第 1 次到第 2 次同步运行。

 //1st function
 function first(){
 $.getJSON("/update/", () => {
   //updates 
  })
 }

 //2nd function
 function second(){
  //triggers some event
 }

此时,我已经尝试使用 Promise,但无济于事,失败了

 //Promise

 var promiseVar = new Promise((resolve, reject) =>{
    first(); //run the first function
             //note: first() will take more time to run because it's
             //grabbing something from the server to update to client
    resolve('Success');
 })

 promiseVar.then((msg)=>{
    console.log(msg);
    second(); 
 })

通过使用 Promise,它在加载第一个函数时仍然执行第二个函数。我怎样才能让这个按顺序运行?

【问题讨论】:

标签: javascript jquery asynchronous promise synchronous


【解决方案1】:

return$.getJSON()first 函数调用,使用.then()。注意jQuery.getJSON() 返回一个 jQuery 承诺对象,.then() 可以链接到

function first() {
  return $.getJSON("/update/")
}

first()
.then(second, (jqxhr, textStatus, errorThrown) => console.error(errorThrown));

function first() {
  return $.Deferred(dfd => {
    setTimeout(() =>
      dfd.resolve("/update/"), Math.floor(Math.random() * 1500))
  }).promise()
}

function second(data) {
  console.log(data);
}

first()
  .then(second
  , (jqxhr, textStatus, errorThrown) => console.error(jqxhr, errorThrown))
  .fail(err => console.error(err)); // handle error for `second` call
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

【讨论】:

  • 这段代码唯一的问题是second的未处理拒绝
  • @JaromandaX (jqxhr, textStatus, errorThrown) =&gt; console.error(errorThrown) 处理从 first 返回的 jQuery 承诺。我们没有second的代码
  • 添加拒绝处理到first(不存在问题),但你没有为second做同样的事情......为什么选择,要么都做,要么都不做:p​​
  • 我会亲自将 Jquery 承诺转换为真正的承诺。因为 Jquery 的很糟糕。例如,编辑您的代码以在秒内引发异常。
  • 这就是为什么我说将 jquery Promise 转换为真正的 Promise,然后 catch 起作用..顺便说一句。如果使用 ES6 使第二个 Promise 成为一种简单的方法,只需使用 async.. 这样做之后,如果您在第二个中抛出一个错误,它就会按预期被捕获。就像我说的那样,如果你现在在第二次抛出错误,它就会被处理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
  • 1970-01-01
  • 2018-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多