[英]How can I use .then() to make a function implement after another in javascript
I am new in javascript. 我是javascript新手。 I have two asynchronous functions, but I would like then implement in some sequence, because the variable in first function will be used in second one.
我有两个异步函数,但是我想按顺序执行,因为第一个函数中的变量将在第二个函数中使用。 following code will explain more specific:
以下代码将更具体地说明:
function1(){
//asynchronous
//generate some variables(a,b)
}
function2(){
//asynchronous
//use a,b
}
so if I just let them implement in this way, some time a,b are not already to be used in function2 some time(some time they are), by my guess they are implemented in parallel, some time function1 completed faster. 因此,如果我只是让它们以这种方式实现,则有时a,b尚未在function2中使用(有时是),以我的猜测,它们是并行实现的,有时function1完成得更快。
I know .then() will return a promise which kinda make one run first, so I am wondering is there some way like: 我知道.then()会返回一个承诺,该承诺首先会执行一次,所以我想知道是否有这样的方式:
funtion1().then(function2());
to make funtion1 implement first then function2 Any suggestion appreciated, let me know if I misunderstand something. 先实现funtion1的功能,然后实现function2的任何建议,如果我误解了,请告诉我。
.then
is a Promise function. .then
是一个Promise函数。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.