0

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
1
  • same issue .. (async () => await start())(); Commented Apr 15, 2020 at 20:05

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

5 Comments

it does work fine, Thank You, but do you have any Explanation why is that needed ?? by the way I tried (async () => await start())(); didn't work, but yours did work
@ATSC: Your approach wrapped the await in an async function, but didn't await that function. This answer wraps the whole thing in an async function and uses await therein. The whole outer function isn't awaited, but it doesn't need to be in this example because nothing happens after it.
Technically await keyword is used to add in order to wait for a Promise. Read further here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@David I tried this and worked fine (async () =>{ console.log('start ....'); await start() ` console.log('done ... ')` })(); But this didn't work,, (async () => await start())(); WHY ??!?
@ATSC: For the same reason this answer does. There is exactly one operation which occurs after the asynchronous operation, the second console log. It will only happen after the async operation if that operation is awaited. The non-working example wraps only the async operation in a function, but doesn't await that function. The working example wraps both operations in a function, and so doesn't need to await that function. Put another console log outside of the wrapping function to see the difference.
1

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 ... ');
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.