如何使用.then()在javascript中实现一个又一个函数
我是javascript新手。 我有两个异步函数,但我想按某种顺序实现,因为第一个函数中的变量将在第二个函数中使用。 以下代码将更具体地解释:如何使用.then()在javascript中实现一个又一个函数,javascript,asynchronous,Javascript,Asynchronous,我是javascript新手。 我有两个异步函数,但我想按某种顺序实现,因为第一个函数中的变量将在第二个函数中使用。 以下代码将更具体地解释: function1(){ //asynchronous //generate some variables(a,b) } function2(){ //asynchronous //use a,b } 因此,如果我只是让它们以这种方式实现,有些时候a,b还没有在函数2中使用过(有些时候是),我猜它们是并行实现的,有些时候函数1完成得更快 我知道。the
function1(){
//asynchronous
//generate some variables(a,b)
}
function2(){
//asynchronous
//use a,b
}
因此,如果我只是让它们以这种方式实现,有些时候a,b还没有在函数2中使用过(有些时候是),我猜它们是并行实现的,有些时候函数1完成得更快
我知道。then()将返回一个承诺,这有点像是先运行一次,所以我想知道是否有这样的方式:
funtion1().then(function2());
先实现功能1,然后实现功能2
任何建议都很感激,如果我误解了什么,请告诉我。。那么
是一个函数
function function1 () {
return new Promise((resolve) => {
console.log('Do your stuff here');
const a = 1;
const b = 2;
resolve({ a, b });
});
}
function function2 ({ a, b }) {
console.log('Do your stuff here', a, b);
}
function1().then(function2)
// Do your stuff here
// Do your stuff here 1 2
谢谢!明白了吗