【问题标题】:Is it possible to create new Promise object in Angular 1.7?是否可以在 Angular 1.7 中创建新的 Promise 对象?
【发布时间】:2020-06-22 07:00:26
【问题描述】:

我有一个当前使用 Angular 1.7 的应用程序,我们有一个 IHTTPPromise (updateCase),然后我们在解决 then() 方法后处理代码

在第一个 then() 之前,我想链接另一个 then() 以设置 x 毫秒的等待时间

我不能只使用setTimeout(),因为它不会返回 Promise。

在 Angular 1.7 中,如何创建一个新的 Promise 来包含 setTimeout 然后解析并允许我链接 then 语句?

this.caseService.updateCase(updateCaseRequest)
//***WANT TO ADD A WAIT HERE
    .then(
    response => {
        this.showUpdateComplete();
        this.getCases();
        this.$scope.selectedCase = selectedCase;
    })
}

【问题讨论】:

标签: angularjs typescript promise ecmascript-5


【解决方案1】:

如果您需要通过使用 then 链中的某些内容来更频繁地延迟请求或其他事情,您可以使用以下内容:

/** Can be used within a then-chain to delay the next then in the chain ;) */
export const delayPromise = (ms: number, value: any) => new Promise((resolve) => { setTimeout(() => resolve(value), ms); });
this.caseService.updateCase(updateCaseRequest)
    .then(res => delayPromise(res, 1000)) // Wait 1 second
    .then(response => {
            this.showUpdateComplete();
            this.getCases();
            this.$scope.selectedCase = selectedCase;
        }
    );

编辑:不能在 angularjs 上下文中使用 - 请参阅 cmets

【讨论】:

  • 使用 delayPromise constm,我收到消息“Promise 仅指一种类型,但在此处用作值”
  • 参数是否互换了? delayPromise(1000,res)?
  • PromisesetTimeout 不应使用/建议。 Angularjs 有专门的服务($q$timeout
  • new Promise 返回的 ES6 Promises 未与 AngularJS 框架及其执行上下文集成。只有在 AngularJS 执行上下文中应用的操作才能受益于 AngularJS 数据绑定、异常处理、属性监视等。
【解决方案2】:

使用 $timeout 服务:

this.caseService.updateCase(updateCaseRequest)
.then( response => {
    return this.$timeout( (_ => response) , delay );
}).then( response => {
    this.showUpdateComplete();
    this.getCases();
    this.$scope.selectedCase = selectedCase;
})

调用$timeout的返回值是一个promise,当延迟过去并执行超时函数(如果提供)时会解决。

有关详细信息,请参阅

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多