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

查看:30
本文介绍了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.我不希望 f2f1 完成之前开始.有没有办法等待所需的时间,而不是更多或更少?

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天全站免登陆