【问题标题】:How to execute second function only after first one is finished? [duplicate]如何仅在第一个功能完成后才执行第二个功能? [复制]
【发布时间】:2019-04-14 18:57:54
【问题描述】:

我有 2 个独立的函数,它们都在发出 GET 请求。 完成后,我需要将 response1 中的数字与 response2 中的数字相加。所以基本上我想要制作第三个函数,它将前两个函数的结果相加。 问题是第 3 个函数在第 1 个和第 2 个函数之前执行。

我尝试了回调,但似乎没有按预期工作。下面你可以找到一个简单的例子,我想在我的代码中实现它之前了解基础知识。我试过的回调示例:

function first(callback){
    setTimeout(function(){
        console.log(1);
    }, 500);
    callback()
}

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

function third(){
    first(second);
}

third();

没有回调的例子:

function first(){
    setTimeout(function(){
        console.log(1);
    }, 500);
}

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

function third(){
    first();
    second();
}

third();

https://jsfiddle.net/u8a592pz/

目前这个函数执行为:

2
1

我想得到什么:

1
2

【问题讨论】:

  • I tried callbacks 我没看到他们。将回调传递给在超时完成后运行的first,并将传递的回调设为second
  • 因为setTimeout()函数,它会这样显示,你的结果显示了500ms,删除它应该可以解决问题。
  • @CertainPerformance 你能帮我回电吗,也许我理解错了?稍后将用我尝试过的内容更新我的问题。 @AkashJain setTimeout() 需要模拟执行第一个函数的延迟
  • 您需要在超时结束后调用回调,而不是之前。修复它,它应该可以按预期工作

标签: javascript jquery function callback


【解决方案1】:

将first 的内容包装在一个Promise 中并返回。并将third 设为async 函数并在first() 之前使用await

function first(){
    return new Promise(res => {
      setTimeout(function(){
        console.log(1);
        res();
      }, 500);
    })
}

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

async function third(){
    await first();
    second();
}

third();

【讨论】:

  • @moonrider_unchained 很高兴它有帮助。如果您认为答案正确,请考虑接受。
猜你喜欢
  • 1970-01-01
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-21
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
  • 2020-11-12
相关资源
最近更新 更多