【问题标题】:How to resolve chained promise between services in Angular?如何解决 Angular 中服务之间的链式承诺?
【发布时间】:2020-01-16 19:49:20
【问题描述】:

我的 Angular 项目中有一个 dynamo db 服务,它通过一系列承诺返回一个承诺,该承诺从 cognito 获取一个 subId,然后将该 subId 传递给一个 dyamodb get 查询:

async getUserObject(): Promise<any> {
    var promise = new Promise((resolve, reject) => {
        setTimeout(() => {
            let response; 
            let cognitoUser = this.cognitoUtil.getCurrentUser();
            cognitoUser.getSession(function (err, session) {
            if (err)
                console.log("UserParametersService: Couldn't retrieve the user");
            else {
                //Here were grabbing the subId and returning a promise 
                cognitoUser.getUserAttributes(
                    function getSubId(err, result) {
                        let cognitoSubIdPromise = new Promise((resolve,reject) => {
                            setTimeout(() => {
                                if (err) {
                                    reject('error');
                                } else {
                                    let response: any = result[0].getValue();
                                    resolve(response);
                                }
                            }, 1000);
                        });
                        //Once we've resolved the subId from Cognito we can plug it into our dynamodb query
                        cognitoSubIdPromise.then((val) => {
                            let clientParams:any = {
                                params: {TableName: environment.ddbTableName}
                            };
                            if (environment.dynamodb_endpoint) {
                                clientParams.endpoint = environment.dynamodb_endpoint;
                            }
                            var DDB = new DynamoDB(clientParams);
                            var getParams = {
                                TableName: environment.ddbTableName,
                                Key: {
                                    'userId' : {S: val.toString()},
                                }
                            };
                            //Here we are executing the query
                            DDB.getItem(getParams, 
                                function (err, result) {
                                    if (err){
                                        console.log(err)
                                    } else {
                                        console.log("DynamoDBService got user object: " + JSON.stringify(result));
                                        response = result;
                                    }
                                }
                            );
                        });
                    });
                }
            });
          console.log("Async Work Complete");
          resolve(response);
        }, 1000);
      });
      return promise;
}

在另一个用户登录服务中,我试图确保只有在从我的 dynamo db 服务完成 db 查询后,才会执行一个 Cognito 函数回调,该回调在登录后将我们带到应用程序的主页

databaseDynamo.getUserObject().then((data => {
                console.log("this is the resolved data", data);
                console.log("getUserObject function execution done!");
                callback.cognitoCallback(null, session);
           }));

此已解析数据的控制台日志始终返回未定义,并且 cognito 回调函数在已解析数据有值之前执行。如何确保在获得数据值之前不会触发 cognitoCallBack 函数?

【问题讨论】:

    标签: angular typescript promise async-await


    【解决方案1】:

    这是因为你的解析不合适

    async getUserObject(): Promise < any > {
      var promise = new Promise((resolve, reject) => {
        setTimeout(() => {
          let response;
          let cognitoUser = this.cognitoUtil.getCurrentUser();
          cognitoUser.getSession(function (err, session) {
            if (err)
              console.log("UserParametersService: Couldn't retrieve the user");
            else {
              //Here were grabbing the subId and returning a promise 
              cognitoUser.getUserAttributes(
                function getSubId(err, result) {
                  let promise = new Promise((resolve, reject) => {
                    setTimeout(() => {
                      if (err) {
                        reject('error');
                      } else {
                        let response: any = result[0].getValue();
                        resolve(response);
                      }
                    }, 1000);
                  });
                  //Once we've resolved the subId from Cognito we can plug it into our dynamodb query
                  promise.then((val) => {
                    let clientParams: any = {
                      params: { TableName: environment.ddbTableName }
                    };
                    if (environment.dynamodb_endpoint) {
                      clientParams.endpoint = environment.dynamodb_endpoint;
                    }
                    var DDB = new DynamoDB(clientParams);
                    var getParams = {
                      TableName: environment.ddbTableName,
                      Key: {
                        'userId': { S: val.toString() },
                      }
                    };
                    //Here we are executing the query
                    DDB.getItem(getParams,
                      function (err, result) {
                        if (err) {
                          console.log(err)
                          reject(err);//added reject in case of any error
                        } else {
                          console.log("DynamoDBService got user object: " + JSON.stringify(result));
                          response = result;
                          resolve(response); // <--- added resolve to here
                        }
                      }
                    );
                  }); // you should have a error handler here in case the inner promise is rejected
                });
            }
          });
          console.log("Async Work Complete");
          // <------ removed resolve from here
        }, 1000);
      });
      return promise;
    }
    

    你应该检查你的变量名,它可能会让人感到困惑,也许将它命名为内部 promise innerresolve 或其他东西,但这并不重要。我认为移动决心应该解决它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 2015-06-24
      • 2017-04-26
      相关资源
      最近更新 更多