Angular / TypeScript - Call a function after another one has been completed

吃可爱长大的小学妹 提交于 2019-12-09 04:16:42

问题


I would like to call f2 after f1 has been completed. f1 function can be synchronous or asynchronous. I need an example that work in both cases. I have found a solution, using a Promise and a timer:

global() {
    this.f1().then(res => {
        this.f2()
    })
}

f1() {
    return new Promise<any>((resolve, reject) => {

        // Some code...

        setTimeout( () => {
            resolve(x);
        }, 1500);
    });
}

f2() {
    // Some code...
}

The problem is the program always have to wait 1500ms. I don't want f2 start before f1 is finished. Is there a way to wait the time needed, not more or less?


回答1:


So remove the setTimeout part. It will call resolve or reject and then pass the execution to the next then or catch handler. If you have some asynchronous call in the Promise, you need to call resolve/reject in the result of that call.

What about not waiting 1500ms - the given time is actually the lowest time after which the function may be called. Maybe after 2000ms This is related to the main thread in which JS code works. If main thread has no work to done, then the results of the asynchronous calls are going to be executed.

function f1() {
    return new Promise((resolve, reject) => {
        console.log('f1');
        resolve();
    });
}

function f2() {
   console.log('f2');
}

f1().then(res => f2());



回答2:


If f1 is synchronous, there is nothing special to do:

global() {
    f1();
    f2();
}

If f1 is asynchronous and return an Observable, use Rxjs operator, like concatMap:

global() {
    f1().concatMap(() => f2());
}

If f1 is asynchronous and return a Promise, use async/await:

async global() {
    await f1();
    f2();
}

If f1 is asynchronous and return a Promise (alternative):

global() {
    f1().then(res => f2());
}



回答3:


Just remove the timeout

function f1() {
    return new Promise((resolve, reject) => {
        console.log('i am first');
        resolve();
    });
}

function f2() {
    console.log('i am second');
}

f1().then(f2);


来源:https://stackoverflow.com/questions/48538814/angular-typescript-call-a-function-after-another-one-has-been-completed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!