Search code examples
angularrxjses6-promise

Angular - Promises with call back


I'm learning promises in Angular.

I have this function:

  myFunction(): Promise<any> {
    return new Promise(resolve => {
      resolve(this.cognitoUtil.updateAtributes(this.id, this.userProfileForm));
    });
  }

Inside of the method cognitoUtil.updateAtributes, there are a methods that are called and I have the log console.log("callback") after the methods are executed:

updateAtributes(id: string, user: UserForm) {

const cognitoUser = this.getCurrentUser();
cognitoUser.getSession(function (err, session) {
  if (err) {
    return;
  }
  const attributeList = [];
  const dataName = {
    Name: 'name',
    Value: user.name
  };
  const dataEmail = {
    Name: 'email',
    Value: user.email
  };
  attributeList.push(new CognitoUserAttribute(dataName));
  attributeList.push(new CognitoUserAttribute(dataEmail))
  cognitoUser.updateAttributes(attributeList, function (error, result) {
    if (error) {
      alert(err);
      return;
    }
    console.log("callback");
  });

});
} 

The promise is called in this way:

this.myFunction().then(() => console.log('Inside the promise'));

When the promise is called, the log inside the promise appears before the log callback:

enter image description here

Why is it happening that? How can I do to have the log Inside the promise after the log callback.


Solution

  • your promise is resolved immediately, the code inside the Promise constructor is synchronous (there is no waiting in there, nothing to be postponed)

    this is why you get your promise immediately resolved at the same moment when you call it

    there is no need for promise there in the first place, just do what you do without a promise and you will get it straight

    UPDATE: it looks like updateAttributes is calling its callback at a random time which is way after callback of then

    if you want to get it straight you need to wrap your call to updateAttributes into a promise:

    myFunction(): Promise<any> {
        return wrappedUpdateAttributes(this.id, this.userProfileForm);
    }
    
    function wrappedUpdateAttributes(id, cognitoUser) {
       // ...
       return new Promise(resolved => {
          cognitoUser.updateAttributes(attributeList, function (error, result) {
              // ...
              resolve(undefined);
          })
       });
    
    }
    
    this.myFunction().then(() => console.log('Inside the promise')); // <-- should work