如何使用Promise中的值异步更新AngularJS状态

时间:2017-04-06 15:22:35

标签: javascript angularjs

如何在JavaScript中从then()访问返回值?

我有以下功能:

function getResult(){
  var promise = _myService.getAge();
  var getResultPromise = promise.then(function(age){
    return age;
  })
  return getResultPromise; //How do i get the age (value) here?  *see image*
}

或者我将如何访问下面的$$状态对象中的值?

enter image description here

1 个答案:

答案 0 :(得分:-2)

这个怎么样:



//The simple solution, this is how to use a Promise:

let _myService = {
  getAge: function() {
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve(3)
      }, 500);
    })
  }
};

function getResult() {
  _myService.getAge().then(function(age) {
    console.log(age);
  });
}

getResult();

//OR, maybe closer to OP's intended implementation, put the value in an outer state:

let outerState = {
  age: 0
};

setTimeout(function() {
  console.log(outerState)
}, 450);

let _myService2 = {
  getAge: function() {
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve(8)
      }, 750);
    })
  }
};

function addAgeToOuterState() {
  pState = new Promise(function(resolve, reject) {
    _myService2.getAge().then(function(newAge) {
      outerState.age = newAge;
      resolve(outerState);
    });
  });

  pState.then(function() {
    console.log(outerState);
  });

  return pState;
}

addAgeToOuterState()

//for fun
.then(function(outer) {
  console.log(outer); //state is still here
});