将 http 请求嵌套在承诺列表中



我有一个返回承诺列表的服务函数

getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}

,我在控制器中调用:

validateUser() {
     this.error = null;
     this.service.getData(this.$scope.username)
        .then(resp => {
            if (resp.userInfo.data.user) {
                this.service.storeUserData('userData', JSON.stringify(resp));
                this.$location.path('/profile');
            } else {
                this.error = resp.userInfo.data.message;
            }
        })
}

到目前为止工作正常,但我正在寻找的是操纵我从userChart请求中获得的数据。

我想操纵我从调用userChart中获得的 json,将其中一些存储在数组中,并发出另一个请求,该请求使用初始请求中存储的数组对象值作为参数返回数据。

所以基本上我不需要来自userChart的json,我只需要使用它的一些数据发出嵌套(?(请求。

如果从then返回承诺,则原始承诺的调用方将等待,直到解析嵌套承诺。调用方是使用 $q.all 或其他东西的服务并不重要,它是链接的。

这只显示相关的代码,它位于您的服务中,其他所有内容保持不变。

userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
    .then((result) => {
       // additional manipulation if needed on result
       // second call to http and return the resulting promise
       return this.$http.doSomething('');
    });

我还没有尝试过这个,但也许你可以在它回来后立即对该调用的结果做点什么? 像这样的东西?

getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user)).
          then(function(response) {
            // Do something with the successful response
          }, function(response) {
            // Do something for the failed response
          })
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}

如果我了解您的需求,您应该首先获得图表响应,然后使用该响应调用其他 Web 服务,因此这样的事情应该有效:

validateUser() {
    this.getData({})
        .then(function (response) {
            // response containing 'userInfo' and 'userTopArtists'
            console.log(arguments);
        });
}
getData(user) {
    const me = this;
    return me.$http.get('https://jsonplaceholder.typicode.com/users')
        .then(function (charts) {
            return me.$q.all({
                // use charts as param for other calls...
                userInfo: me.$http.get('https://jsonplaceholder.typicode.com/users'),
                userTopArtists: me.$http.get('https://jsonplaceholder.typicode.com/users')
            });
        })
        .catch(err => {
            me.$q.reject('Error' + err.status);
        });
}

最新更新