Javascript 构建承诺对象的有效方法

Javascript 构建承诺对象的有效方法,javascript,ecmascript-6,promise,Javascript,Ecmascript 6,Promise,目前我所拥有的是: 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.b

目前我所拥有的是:

    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 => {
                let promises = [];
                let data = resp.data.weeklychartlist.chart;
                for (let i = data.length - 4; i < data.length; i++) {
                    promises.push(
                        this.$http.get(this.buildUrl('user.getWeeklyTrackChart', user) + `&from=${data[i].from}&to=${data[i].to}`)
                        .then(resp => {
                            return resp.data.weeklytrackchart.track.length;
                        })
                    );
                }

                return this.$q.all(promises);
            })
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}
  • 这种方法有意义吗?我应该使用它吗
  • 您可以看到,我在第一个函数中发出的第三个请求有其他嵌套请求。有没有什么方法可以将其集成到我上面写的方法中

  • 是的,这样概括总是个好主意。然而:

    • `${methods[method]}`
      是对模板字符串的无意义使用
    • 您的方法/属性名称在大写和前缀方面不一致(
      user…
      vs
      get…
    • 您的
      catch
      回调没有任何作用。它至少应该返回被拒绝的承诺,或者干脆抛出错误。还有
    关于图表列表,您只需在调用
    all
    之前在承诺中添加另一个
    ,然后再添加一个
    。此外,您还可以通过使用更具功能性的方法大大简化回调:

    getData(user) {
        const methods = ['Info', 'TopArtists', 'WeeklyChartList'];
        let promises = {};
        for (let method of methods) {
            obj['user' + method] = this.$http.get(this.buildUrl('user.get'+method.toLowerCase(), target));
        }
        promises.userWeeklyChartList = promises.userWeeklyChartList.then(resp =>
             this.$q.all(resp.data.weeklychartlist.chart.slice(-4).map(val =>
                 this.$http.get(this.buildUrl('user.getWeeklyTrackChart', user) + `&from=${val.from}&to=${val.to}`)
             ).then(resp =>
                 resp.data.weeklytrackchart.track.length
             ))
        );
        return this.$q.all(promises).catch(err => {
            throw new Error(err.status);
        });
    }
    

    是的,这样概括总是个好主意。然而:

    • `${methods[method]}`
      是对模板字符串的无意义使用
    • 您的方法/属性名称在大写和前缀方面不一致(
      user…
      vs
      get…
    • 您的
      catch
      回调没有任何作用。它至少应该返回被拒绝的承诺,或者干脆抛出错误。还有
    关于图表列表,您只需在调用
    all
    之前在承诺中添加另一个
    ,然后再添加一个
    。此外,您还可以通过使用更具功能性的方法大大简化回调:

    getData(user) {
        const methods = ['Info', 'TopArtists', 'WeeklyChartList'];
        let promises = {};
        for (let method of methods) {
            obj['user' + method] = this.$http.get(this.buildUrl('user.get'+method.toLowerCase(), target));
        }
        promises.userWeeklyChartList = promises.userWeeklyChartList.then(resp =>
             this.$q.all(resp.data.weeklychartlist.chart.slice(-4).map(val =>
                 this.$http.get(this.buildUrl('user.getWeeklyTrackChart', user) + `&from=${val.from}&to=${val.to}`)
             ).then(resp =>
                 resp.data.weeklytrackchart.track.length
             ))
        );
        return this.$q.all(promises).catch(err => {
            throw new Error(err.status);
        });
    }
    

    作为第一个通行证,以下是我将如何使用它

    
    const{$http:{get},$q:{all}}=this,
    //将{x:'a',y:'b'}转换为'&x=a&y=b'
    paramStr=obj=>Object.entries(obj).map([k,v])=>`&${k}=${v}`)。join(),//您可能没有对象#项;这是新的
    getUrl=(target,method,params={})=>this.buildUrl(`user.get${method}`,target)+paramStr(params),
    getData=user=>all(Object.assign({}),
    …['info','topartists','WeeklyChartList'].map(m=>get(getUrl(user,m)))
    ))
    .then([userInfo,userTopArtists,{data:{weeklychartlist:{chart}}])=>
    全部({
    用户信息,
    艺术家们,
    用户图表:全部([
    …图表切片(-4)
    .map({from,to})=>
    get(getUrl(目标,'WeeklyTrackChart',{from,to}))
    .then({data:{weeklytrackchart:{track:{length}}}})=>length)
    )
    ])
    })
    )
    
    .catch(({status})=>this.$q.reject(`Error${status}`))作为第一步,下面是我将如何使用它

    
    const{$http:{get},$q:{all}}=this,
    //将{x:'a',y:'b'}转换为'&x=a&y=b'
    paramStr=obj=>Object.entries(obj).map([k,v])=>`&${k}=${v}`)。join(),//您可能没有对象#项;这是新的
    getUrl=(target,method,params={})=>this.buildUrl(`user.get${method}`,target)+paramStr(params),
    getData=user=>all(Object.assign({}),
    …['info','topartists','WeeklyChartList'].map(m=>get(getUrl(user,m)))
    ))
    .then([userInfo,userTopArtists,{data:{weeklychartlist:{chart}}])=>
    全部({
    用户信息,
    艺术家们,
    用户图表:全部([
    …图表切片(-4)
    .map({from,to})=>
    get(getUrl(目标,'WeeklyTrackChart',{from,to}))
    .then({data:{weeklytrackchart:{track:{length}}}})=>length)
    )
    ])
    })
    )
    
    .catch(({status})=>this.$q.reject(`Error${status}`))我个人会保持原样,这个
    buildPromiseObj
    收获很少,只给你带来了另一个问题。我个人会保持原样,这个
    buildPromiseObj
    收获很少,只给你带来了另一个问题。欣赏深入的回应,但我得到了这个严重的错误,在过去的半个小时里,我一直试图解决的问题是
    TypeError:无法读取promises.userweeklychartlist.promises.userweeklychartlist.then.resp
    weeklychartlist的未定义属性“chart”:让data=resp.data.weeklychartlist.chart@你是不是写了一个点而不是作业?没有
    promises.userweeklychartlist.promises.userweeklychartlist.th‌​en.resp
    任何地方。访问
    .data
    属性的唯一位置是
    resp.data.weeklychartlist
    @MichaelRosefield不确定您的意思,我的answer@Bergi我复制了你写的代码,这就是为什么我对为什么会发生这个错误有疑问。请欣赏深入的回应,但是我得到了这个严重的错误,在过去的半个小时里,我一直试图解决的问题是
    TypeError:无法读取promises.userweeklychartlist.promises.userweeklychartlist.then.resp
    weeklychartlist的未定义属性“chart”:让data=resp.data.weeklychartlist.chart@你是不是写了一个点而不是作业?没有
    promises.userweeklychartlist.promises.userweeklychartlist.th‌​en.resp
    任何地方。访问
    .data
    属性的唯一位置是
    resp.data.weeklychartlist
    @MichaelRosefield不确定您的意思,我的answer@Bergi我完全按照您编写的代码复制了代码,这就是为什么我对为什么会发生此错误有疑问的原因。