typescript 向返回承诺的javascript方法添加延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39495551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:51:01  来源:igfitidea点击:

Add delay to javascript method that returns promise

angulartypescriptpromisetimeoutsettimeout

提问by Rethic

I'm currently trying to learn Angular 2, typescript, promises, etc. I've setup a small app for developer tools and a service that just returns hard-coded data. This is to be used for testing purposes only.

我目前正在尝试学习 Angular 2、打字稿、promises 等。我已经为开发人员工具设置了一个小应用程序和一个只返回硬编码数据的服务。这仅用于测试目的。

I'd like to add short timeout on the service method to simulate server lag for testing some of my controls, but I can't find the correct syntax to do so. How can I add a 5 second delay to my service call?

我想在服务方法上添加短超时以模拟服务器延迟以测试我的一些控件,但我找不到正确的语法来这样做。如何为我的服务呼叫添加 5 秒延迟?

Developer Tools Service

开发者工具服务

@Injectable()
export class DeveloperService {
    getExampleData(): Promise<ExampleItem[]> {
        const examples: ExampleItem[] = [];
        examples.push({ id: 1, name: 'Spaceman Spiff', location: 'Outer Space', age: 12 });
        examples.push({ id: 2, name: 'Stupendous Man', location: 'The City', age: 30.5 });
        examples.push({ id: 3, name: 'Tracer Bullet', location: 'The City', age: 24 });
        examples.push({ id: 4, name: 'Napalm Man', location: 'War Zone', age: 43.333 });
        examples.push({ id: 5, name: 'Adult Calvin', location: 'In the future', age: 54 });

        // TODO: Slow down this return!
        return Promise.resolve(examples);
    }
}

Developer Tools App

开发者工具应用

getExampleData() {
    return (): Promise<Array<any>> => {
        return this.developerService.getExampleData();
    };
}

UPDATE: 1I have tried adding the setTimeout() to the call for control I'm attempting to implement, but it never populates the data at that point. I'd really like to get the delay into the service call method so I don't have to remember implementing it repeatedly.

更新: 1我曾尝试将 setTimeout() 添加到我试图实现的控制调用中,但它从未在那时填充数据。我真的很想在服务调用方法中加入延迟,这样我就不必记住重复实现它。

getExampleData() {
    setTimeout(() => (): Promise<Array<any>> => {
        return this.developerService.getExampleData();
    }, 3000);
}

回答by Estus Flask

Delayed native promise

延迟的原生承诺

New promise that resolves with undefined

解决的新承诺 undefined

return new Promise(resolve =>
  setTimeout(resolve, 5000)
);

New promise that resolves with a value

用值解决的新承诺

return new Promise(resolve => 
  setTimeout(() => resolve(value), 5000)
);

Existing promise

现有承诺

return promise.then(value => 
  new Promise(resolve => 
    setTimeout(() => resolve(value), 5000)
  )
);

Delayed Bluebird promise

延迟的蓝鸟承诺

Bluebird promise library has better performance and convenient features that can be used out of the box to delay promise chains.

Bluebird 承诺库具有更好的性能和方便的功能,可以开箱即用地延迟承诺链。

New promise that resolves with undefined

解决的新承诺 undefined

return Bluebird.delay(5000);

New promise that resolves with a value

用值解决的新承诺

return Bluebird.resolve(value).delay(5000);
// or
return Bluebird.delay(5000).return(value);

Existing promise

现有承诺

return bluebirdPromise.delay(5000);

Delayed promise with RxJS

延迟承诺与 RxJS

RxJS is already used in Angular 2/4 projects and can be used to create or transform promises with RxJS operators and small overhead.

RxJS 已经在 Angular 2/4 项目中使用,可用于使用 RxJS 操作符和小开销创建或转换承诺。

New promise that resolves with undefined

解决的新承诺 undefined

return Observable.of().delay(5000).toPromise();
// or
return Observable.interval(5000).first().toPromise();

New promise that resolves with a value

用值解决的新承诺

return Observable.of(value).delay(5000).toPromise();

Existing promise

现有承诺

return Observable.fromPromise(promise).delay(5000).toPromise();

回答by Dorus

Delayed result with RxJS 6

RxJS 6 延迟结果

You can use the following code to delay values in RxJs 6 by nms.

您可以使用以下代码将 RxJs 6 中的值延迟nms。

With no specific value (will emit 0)

没有特定值(会发出0

return timer(n);

With a set value

有设定值

return of(value).pipe(delay(n));

or

或者

return timer(n).pipe(mapTo(value));

from a promise

来自承诺

return from(promise).pipe(delay(n));

to return a promise

回一个承诺

put .toPromise()on any of the previous examples afterthe pipe.

.toPromise()任何的前面的例子pipe

return timer(n).toPromise();
return of(value).pipe(delay(n)).toPromise();

etc.

等等。