Angular/TypeScript-在另一个函数完成后调用一个函数 [英] Angular / TypeScript - Call a function after another one has been completed

查看:500
本文介绍了Angular/TypeScript-在另一个函数完成后调用一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在f1完成后给f2打电话. f1功能可以是同步异步.我需要一个在两种情况下都能工作的示例.我找到了使用Promise和计时器的解决方案:

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...
}

问题在于程序始终必须等待 1500ms .我不想在f1完成之前开始f2. 有没有办法等待所需的时间,而不是更多或更少?

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?

推荐答案

因此,请删除setTimeout部分.它将调用resolvereject,然后将执行传递给下一个thencatch处理程序.如果Promise中有一些异步调用,则需要在该调用的结果中调用resolve/reject.

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.

不等待怎么办1500ms-给定的时间实际上是可以调用该函数的最短时间.可能在2000ms之后,这与JS代码在其中工作的主线程有关.如果主线程没有工作要做,则将执行异步调用的结果.

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

这篇关于Angular/TypeScript-在另一个函数完成后调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆