0

Current situation: I'm having a code that is handling API. And im trying to map it and return it as a string.

const C = this.functionA('ID_123').then(function(value) { 
   console.log("JR TEST 3", value.user.name); 
   return value.user.name;
});

The code above is to call the function and under 'JR TEST 3' console it return this result which is correct: JR TEST 3 USERNAME

But when I use

const C = this.functionA('ID_123').then(function(value) { 
   console.log("JR TEST 3", value.user.name); 
   return value.user.name;
});
console.log('JR TEST 4', C);

This will return me this: enter image description here

Anyone know how to solve this?

tedeeee
  • 47
  • 5
  • .then() returns a promise again, so you basically have two choices deal with the result as in the first example or use async/await syntax `await this.function(...`. If you can provide more info on how/where you want to use that mapped value, it will make it easier to suggest exact change. Meanwhile reading this might help https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining – ggat Jul 01 '22 at 03:50
  • Sorry I forget to mentioned: I cannot use await because that code i called is inside a forEach @ggat – tedeeee Jul 01 '22 at 03:51
  • then easiest is to change forEach to `for` or `for...of` loop and use `await` syntax – ggat Jul 01 '22 at 03:59
  • Consider asking the right question, then you'll be able to get the right answer. This totally depends on what happens in your code. async/await is much better suited to work with loops. It's possible to do everything it does with raw promises but this may be not straightforward at all. You may want to reconsider the reasons you don't use async/await, probably they are not valid enough. – Estus Flask Jul 01 '22 at 05:55

0 Answers0