ATSC
ATSC

Reputation: 3

Async / Await JavaScript issue

shortly, I was trying to simulate async / await behavior in JavaScript but getting not expected

const urls = ['api1', 'api2', 'api3']

async function start() {
  for (i = 0; i < urls.length; i++) {
    result = await getFromApi(urls[i])
    console.log(result)
  }
}

async function getFromApi(apiUrl) {
  return await new Promise((resolve, reject) => {
    resolve(apiUrl)
  }).then(apiUrl => apiUrl)
}

console.log('start ....')
start()
console.log('done ... ')

so the expected result should be

start ....
api1
api2
api3
done ... 

but I am getting

start ....
done ... 
api1
api2
api3

Upvotes: 0

Views: 122

Answers (2)

David
David

Reputation: 218818

start() isn't being awaited. If this is at the top-level scope then you would probably use .then() on the returned Promise object. For example:

console.log('start ....');
start().then(() => {
    console.log('done ... ');
});

Upvotes: 1

norbitrial
norbitrial

Reputation: 15166

The function called start() needs be used with await. Also in the same time your code needs to be wrapped with async function.

Try as the following:

(async () => {
    const urls = ['api1', 'api2', 'api3']

    async function start() {
        for (i = 0; i < urls.length; i++) {
            result = await getFromApi(urls[i])
            console.log(result)
        }
    }

    async function getFromApi(apiUrl) {
        return await new Promise((resolve, reject) => {
            resolve(apiUrl)
        }).then(apiUrl => apiUrl)
    }

    console.log('start ....')
    await start()
    console.log('done ... ')
})();

I hope this helps!

Upvotes: 1

Related Questions