仅在第一个功能完成后如何执行第二个功能?

时间:2019-04-14 18:57:55

标签: javascript jquery function callback

我有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

1 个答案:

答案 0 :(得分:2)

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

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

相关问题