简体   繁体   English

async-await 是否仅与 Promise 一起使用?

[英]Is async-await only used with promises?

I am using javascript.我正在使用 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?映射是否可能花费太长时间并且可能会记录undefined的内容? So should I use async-await or is it only reserved for promises?那么我应该使用 async-await 还是只为 promise 保留?

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. map总是返回一个数组,所以没有。

The array might contain undefined values though.该数组可能包含未定义的值。

So should I use async-await or is it only reserved for promises?那么我应该使用 async-await 还是只为 promise 保留?

You can only usefully await a promise.您只能等待 promise。

map will return an array, so you can't usefully await it. map将返回一个数组,因此您无法等待它。

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. 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. Map 是同步的。
It accepts a callback function (someFuntion) and always creates a new array.它接受回调 function (someFuntion)并始终创建一个新数组。
The callback function (someFuntion) is not event driven.回调 function (someFuntion)不是事件驱动的。
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.但返回数组中的值将取决于您提供给 map 的回调 function。
If someFuntion returns nothing you will get array of undefined.如果someFuntion什么都不返回,你将得到未定义的数组。
If returns promise then array of promise which can be resolved.如果返回 promise 则 promise 数组可以解析。 Promise.all . Promise.all

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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