Kinesias
Kinesias

Reputation: 454

async/await: can't access array value of function directly

This works:

var getArray = function(id) {
  return [1, 2];
}

console.log(getArray()[0]); // returns 1

This does not work:

var getArray = async function(id) {
  return [1, 2];
}

console.log(await getArray()[0]); // syntax error

Why? How can I change the async/await syntax so it works?

Upvotes: 3

Views: 1273

Answers (3)

user3136781
user3136781

Reputation: 91

A clearer way to do it is via ES6 destructuring:


const [ topBid ] = await getBids(symbol)

// ^^^ it's the same as:

const topBid = (await getBids(symbol))[0]
      

In case you need not the first element of an array, there're various destructuring patterns for different scenarios:

https://www.deadcoderising.com/2017-03-28-es6-destructuring-an-elegant-way-of-extracting-data-from-arrays-and-objects-in-javascript/

Upvotes: 0

Kinesias
Kinesias

Reputation: 454

I found the solution, it's very simple. Just wrap the await part with parentheses.

var first = (await getArray())[0];

Upvotes: 5

Suren Srapyan
Suren Srapyan

Reputation: 68665

You can use await keyword in another async function to get the desired result via - (await getArray())[0].

If you use async function not inside another async function, it must be used like simple Promise function with calling then.

var getArray =  async function(id) {
    return [1,2];
}

getArray().then(res => console.log(res[0])).catch(err => {/* ... */});

If you want to use await, you need another wrapper async function which will do the logic there and will be just called. Also you can use try/catch within your function

var getArray =  async function(id) {
    return [1,2];
}

async function printFirst() {
  try {
     const first = (await getArray())[0];
     console.log(first);
  } catch(e) {
  
  }
}

printFirst();

Upvotes: 1

Related Questions