0

I have a promise, which gets the credentials from http://someurl/credentials.

const credentials = await this._axiosSomeVar.get(`/credentials/${serviceName}`)
return credentials

As you can see, I return the promise object. And it works as well. But now I need to return the Map() object, which contains pair username & password. Something like:

return new Map(credentials.data.username, credentials.data.password)

But it is just pseudo code and, unfortunately, search in google did not help me to make it works.

  • Post the full code you've tried. What you have looks ok so far, so we need more context to see how it failed. –  Jul 15 '19 at 08:33
  • Possible duplicate of [How to convert a plain object into an ES6 Map?](https://stackoverflow.com/questions/36644438/how-to-convert-a-plain-object-into-an-es6-map) – zronn Jul 15 '19 at 08:33
  • It is not clear what you are trying to achive: make a promise that resolves with a map or return a map intstead of a promise? Just to be clear the later wont work. – Yury Tarabanko Jul 15 '19 at 08:39
  • Is this another question about how to get the value out of the promise? Or in other terms, how to get the result before it is computed? – Thomas Jul 15 '19 at 08:45
  • @ChrisG actually this is a full code. As you can see from the first code snippet, I return the promise object (`credentials`), but I need somehow to get the data from this promise and return it – Tireless Coder Jul 15 '19 at 08:46
  • 1
    Since you have `await` in there, that piece of code should assign the result to `credentials,`, not the pending Promise. So if you do `return credentials.data` instead, the calling function will receive the response, provided it is also called with `await`. Also, code that contains `return` but not the surrounding function is my no means "full code"; I'm asking about the calling context etc. –  Jul 15 '19 at 09:19

1 Answers1

0

It looks like there's two issues: a function that will await something needs to be also called with await, otherwise the function won't return the result but the Promise itself.

Next, a Map is supposed to receive an iterable that contains key-value arrays; it also only accepts a single parameter.

Here's a live example of a user map, using a placeholder API:

class App {
  constructor() {
    this._axiosSomeVar = axios;
  }

  async getUserMap() {
    const { data } = await this._axiosSomeVar.get("https://jsonplaceholder.typicode.com/users")
    // map user array to array of key-value arrays
    return new Map(data.map(user => [user.username, user.email]));
  }

  async main() {
    this.userMap = await this.getUserMap();
    console.log(this.userMap); // check browser console to see actual map
 }
}

new App().main();
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>