简体   繁体   中英

Is async-await only used with promises?

I am using javascript.

My question comes from this scenario: I have a large array I am mapping through,

let myNewArray = myLargeArray.map(someFuntion)
console.log(myNewArray)

Is it possible that the mapping might take too long and that undefined might be logged? So should I use async-await or is it only reserved for promises?

Is it possible that the mapping might take too long

"too long" is subjective. The time it takes won't have any impact on the value you end up with though.

that undefined might be logged?

map always returns an array, so no.

The array might contain undefined values though.

So should I use async-await or is it only reserved for promises?

You can only usefully await a promise.

map will return an array, so you can't usefully await it.

If someFunction returns a promise, then the map will return an array of promises, which you could wrap with Promise.all which returns a promise that you could await if you wanted to log an array of resolved values instead of an array of promises.

Map is synchronous.
It accepts a callback function (someFuntion) and always creates a new array.
The callback function (someFuntion) is not event driven.
It is applied for every element in the array once in-order.
You will always receive an array and not undefined. But values inside the returned array will depend on the callback function you provide to map.
If someFuntion returns nothing you will get array of undefined.
If returns promise then array of promise which can be resolved. Promise.all .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM