代码之家  ›  专栏  ›  技术社区  ›  Rafael de Castro

服务承诺为组件上的另一个承诺返回处理过的数据

  •  0
  • Rafael de Castro  · 技术社区  · 6 年前

    对于那些问原因的人来说,这是因为我可以在我的服务中保证,返回的数据将根据我的文件需要进行处理和调整。。

    情景01==我所拥有的==

    myFile.ts文件

    methodReturnPromise()
        .then( data => { /* Sucess, Do This */} )
        .catch( err => { /* Failure, Do This Instead */} );
    

    服务.ts

    myServiceMethod(): Promise<any> {
        methodReturnPromise()
            .then( data => { /* Sucess, Treat and return */} )
            .catch( err => { /* Failure, Do This Instead and return */} );
    }
    

    myFile.ts文件

    this.myService.myServiceMethod()
        .then( data => { /* Success, Do this */})
        .catch( err => { /* Failure, Do This Instead */} );
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   lmarqs    6 年前

    你可以用 then catch myServiceMethod() 对于这样的事情:

    myServiceMethod(): Promise<any> {
        return methodReturnPromise()
            .then( data => { 
                /* Success, do something here and return the same data received */ 
                return data; 
             } )
            .catch( err => { 
                /* Failure, do something here and rethrow the same error */
    
                throw err;
            } );
    }
    

    var promise1 = new Promise(function(resolve, reject) {
      resolve("ok");
    });
    
    promise1.then(function(data) {
        console.log("log1", data);
        return data;
      })
      .then(function(data) {
        console.log("log2", data);
      });
    
    var promise2 = new Promise(function(resolve, reject) {
      reject("ERROR");
    });
    
    promise2.catch(function(err) {
        console.error("error1", err);
        throw err;
      })
      .catch(function(err) {
        console.error("error2", err);
      });