-1

I have the below code:

vm.testService.getUser(id, name)
.then((resultA) => {
    return vm.testService.getUserInfo(id, name);
})
.then(() => {
    // will process resultA from first .then
});

I need to access resultA on the second .then. Thanks in advance.

jengfad
  • 704
  • 2
  • 8
  • 20

2 Answers2

0

One way is to assign the response of the first then to a variable and access that variable in the second then

check the code snippet

let response

vm.testService.getUser(id, name)
  .then((resultA) => {
    response = resultA
    return vm.testService.getUserInfo(id, name);
  })
  .then(() => {
    console.log(response)
    // will process resultA from first .then
  });
Geeky
  • 7,420
  • 2
  • 24
  • 50
  • I've already thought of assigning it to a higher scope variable. But aside from this, is there any other way? – jengfad Mar 31 '17 at 15:17
  • Can't answer the question anymore, but you can return an array [resultA, vm.testService.getUserInfo(id, name)] or use Promise.all as well. – Ronan Mar 31 '17 at 15:17
  • Marking this as an answer since this has less risk on our current implementation. Thanks! – jengfad Apr 11 '17 at 10:22
0

You could store the result of the first callback in the external scope

let result;
vm.testService.getUser(id, name)
.then((resultA) => {
    result = resultA;
    return vm.testService.getUserInfo(id, name);
})
.then(() => {
    // 'result' will now equal resultA
});
Jordan Burnett
  • 1,799
  • 8
  • 11