简体   繁体   中英

Fastest way to convert callback to array

For instance, perhaps I am getting data from some data-generating process in the form of a callback function. Currently, my code looks something like:

const data = new Array();
generateData((item) => data.push(item));

I am wondering, however, if this is the most efficient way of doing things. I'm relatively new to JavaScript, so perhaps there is some native wrapper around callbacks to give an array with all the individual callback parameters?

I understand there is a way to "promisify" the function, though I'm not certain as to whether the added async stuff is necessary or if its even faster than what I'm already doing.

This is probably the most efficient. This is asynchronous as it is anyways, since the callback is automatically ran when the generateData() function returns. The computer isn't going to wait for generateData((item) => data.push(item)); to continue to the next line.

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