Angular / TypeScript - 在另一个函数完成后调用一个函数
Angular / TypeScript - Call a function after another one has been completed
我想在 f1
完成后打电话给 f2
。 f1
函数可以是 同步 或 异步 。我需要一个在这两种情况下都适用的示例。我找到了一个解决方案,使用 Promise
和一个计时器:
global() {
this.f1().then(res => {
this.f2()
})
}
f1() {
return new Promise<any>((resolve, reject) => {
// Some code...
setTimeout( () => {
resolve(x);
}, 1500);
});
}
f2() {
// Some code...
}
问题是程序总是要等待 1500 毫秒。我不希望 f2
在 f1
完成之前开始。
有没有办法等到需要的时间,不多也不少?
所以删除 setTimeout
部分。它将调用 resolve
或 reject
,然后将执行传递给下一个 then
或 catch
处理程序。如果您在 Promise 中有一些异步调用,则需要在该调用的结果中调用 resolve/reject
。
不等待呢1500ms
- 给定的时间实际上是可以调用该函数的最短时间。可能在2000ms
之后这个跟JS代码工作的主线程有关。如果主线程没有工作要做,那么异步调用的结果将被执行。
function f1() {
return new Promise((resolve, reject) => {
console.log('f1');
resolve();
});
}
function f2() {
console.log('f2');
}
f1().then(res => f2());
只需删除超时
function f1() {
return new Promise((resolve, reject) => {
console.log('i am first');
resolve();
});
}
function f2() {
console.log('i am second');
}
f1().then(f2);
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());
}
我想在 f1
完成后打电话给 f2
。 f1
函数可以是 同步 或 异步 。我需要一个在这两种情况下都适用的示例。我找到了一个解决方案,使用 Promise
和一个计时器:
global() {
this.f1().then(res => {
this.f2()
})
}
f1() {
return new Promise<any>((resolve, reject) => {
// Some code...
setTimeout( () => {
resolve(x);
}, 1500);
});
}
f2() {
// Some code...
}
问题是程序总是要等待 1500 毫秒。我不希望 f2
在 f1
完成之前开始。
有没有办法等到需要的时间,不多也不少?
所以删除 setTimeout
部分。它将调用 resolve
或 reject
,然后将执行传递给下一个 then
或 catch
处理程序。如果您在 Promise 中有一些异步调用,则需要在该调用的结果中调用 resolve/reject
。
不等待呢1500ms
- 给定的时间实际上是可以调用该函数的最短时间。可能在2000ms
之后这个跟JS代码工作的主线程有关。如果主线程没有工作要做,那么异步调用的结果将被执行。
function f1() {
return new Promise((resolve, reject) => {
console.log('f1');
resolve();
});
}
function f2() {
console.log('f2');
}
f1().then(res => f2());
只需删除超时
function f1() {
return new Promise((resolve, reject) => {
console.log('i am first');
resolve();
});
}
function f2() {
console.log('i am second');
}
f1().then(f2);
If
f1
is synchronous, there is nothing special to do:
global() {
f1();
f2();
}
If
f1
is asynchronous and return an Observable, useRxjs operator
, like concatMap:
global() {
f1().concatMap(() => f2());
}
If
f1
is asynchronous and return a Promise, useasync/await
:
async global() {
await f1();
f2();
}
If
f1
is asynchronous and return a Promise (alternative):
global() {
f1().then(res => f2());
}