简体   繁体   English

我如何使用.then()使函数在javascript中接连实现

[英]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.

相关问题 如何使用 javascript 承诺使一个函数等待另一个函数异步完成运行? - How can I use a javascript promise to make one function wait for another to finish running asynchronously? 如何使javascript函数可以在点后使用 - How to make javascript function can use after dot 如何在 javascript 的另一个 function 中使用 function 的变量? - how can i use a variable of a function in another function in javascript? 如何使用Javascript函数作为另一个函数的参数? - How can I use Javascript functions as parameters for another function? 如何使用JavaScript中另一个函数的变量 - How can I use variables from another function in javascript 如何使用另一个Javascript文件中的函数? - How can I use a function from one Javascript file in another? 如何使此javascript函数不使用全局变量? - How can I make this javascript function not use a global variable? 如何使函数使用在另一个函数JavaScript / jQuery上声明的变量 - How do I make a function use a variable that was declared on another function JavaScript/jQuery 如何创建一个JavaScript类或函数,使下面的代码工作? 我不能使用诺言等待 - How to make a JavaScript class or function that will make the following code work? I can't use promise and await 完成另一个功能后,如何使Javascript功能启动? - How to make Javascript functions fire after the completion of another function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM