首页 > 解决方案 > 如何仅在第一个功能完成后才执行第二个功能?

问题描述

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

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

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

标签: javascriptjqueryfunctioncallback

解决方案


将 的内容包装first在 Promise 中并返回。和之前thirdasync功能和使用awaitfirst()

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();


推荐阅读