【问题标题】:confusion about chaining $q promises with angular and typescript关于用 Angular 和 typescript 链接 $q 承诺的困惑
【发布时间】:2023-03-14 03:52:01
【问题描述】:

我对 Qpromisesangulartypescript 非常缺乏经验 - 所以显然明智的选择是尝试将它们全部一起使用!

基本上,我设置了一些方法来返回Q.IPromise<T>,以便我可以将then(f) 语句链接到它们上。它们都工作正常;

public Clear = (): Q.IPromise<IArticle> => {
        var deferred = this.$q.defer();
        this.$http({
            url: String.format('{0}{1}', this.$settings.uri(), '/api/cancel/article'),
            responseType: 'json',
            method: 'GET',
            withCredentials: true
        }).then((response: IArticleRequest) => {
            deferred.resolve(response.data.article);
        }, (response) => {
            deferred.reject(null);
        });
        return deferred.promise;
    }

public Fetch = (id: string):Q.IPromise<IArticleRequestData> => {
        var deferred = this.$q.defer();
        this.$http({
            url: String.format('{0}{1}{2}', this.$settings.uri(), '/api/articles/fetch/', id),
            responseType: 'json',
            method: 'GET',
            withCredentials: true
        }).then((response: IArticleRequest) => {
            deferred.resolve(response.data);
        }, (response) => {
            deferred.reject(null);
        });
        return deferred.promise;
    }

所以我可以这样使用它们;

$articles.Fetch(1).then((r: IArticleRequestData) => {
    $articles.Clear().then((n:IArticle) => {
        console.log('completed!');
    })
});

效果很好 - 正如我所期望的那样。

但现在,我需要 另一个 步骤 - last 调用之类的。另一个then(f) 函数在最外面的函数上运行,但在最里面的函数完成之前不会发生。

总之,我需要这个;

$articles.Fetch(1).then((r: IArticleRequestData) => {
    $articles.Clear().then((n:IArticle) => {
        // inner function completed
    })
}).then((l:any)=> {
    // occurs after everything else is done and inner
    // functions are finished
});

我很难弄清楚如何做到这一点。这甚至可以通过 Promise 的工作方式实现吗?

补充说明

在内部部分添加另一个功能是允许的,但感觉是错误的方法。如果我完全无法弄清楚我要问的方式,或者我试图这样做的方式是错误的,这就是我的“修复”。

我想要外部的额外then,因为内部方法实际上负责解决某些事情,因此它们可能会分裂成其他切线或deferred 方法。

【问题讨论】:

    标签: javascript angularjs typescript promise q


    【解决方案1】:

    只需像这样从内部函数返回承诺:

    $articles.Fetch(1).then((r: IArticleRequestData) => {
        return $articles.Clear()
    }).then((l:any)=> {
        // occurs after everything else is done and inner
        // functions are finished
    });
    

    【讨论】:

    • Hrnm。这仅在调用 Clear 函数时才有效。如果在第一个 then() 中发生不同的事情,我还能做些什么来达到这一步吗?
    • 我不确定你的意思。您可以在 then 方法中返回任何承诺并链接到它。由于您可以做出自己的承诺,因此您可以让他们为所欲为。
    • 我想我明白了。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 2015-02-04
    • 2016-04-24
    • 1970-01-01
    相关资源
    最近更新 更多