node.js map 的用法

map 遍历数组每一个元素并调用回调,并返回一个包含所有结果的数组。
函数声明如下:

    /**
      * Calls a defined callback function on each element of an array, and returns an array that contains the results.
      * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
      * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
      */
    map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];

map函数遍历操作和调用回调函数是同步,会阻塞整个线程直到遍历完成。如果回调函数中有异步操作,不会等异步操作完成而是往下遍历。
如下代码,map 的回调函数是一个同步阻塞函数阻塞线程 10 毫秒,那么遍历 10个成员则会阻塞主线程 100 毫秒。在这 100 毫秒内事件线程内所有的异步回调都不会被调用。下面代码中,当 map 阻塞线程时,setInterval 的回调不会被调用,直到 map 遍历结束。

const TestMapBlock = () => {
    const blockTenMillisecond = () => {
        const before = Date.now();
        while (true) {
            if (Date.now() > before + 10) {
                console.log(`sync task finished`);
                break;
            }
        }
    };
    const ls = [];
    for (let i = 0; i < 10; i++) {
        ls.push(i);
    }
    setInterval(() => {
        console.log('-');
    }, 1);
    ls.map(blockTenMillisecond);
    console.log('map finished');
};
TestMapBlock()

/*output:
sync task finished
省略8个相同的
sync task finished
map finished //遍历完之后才执行该语句
-
// 省略多个相同的
-
*/

如下代码 map 的回调函数中包含异步操作,map 在调用回调函数时不会阻塞,继续往下执行,异步操作的回调直到异步完成后才会被调用。

const MapAsyncCallback = () => {
    const asyncOperation = (value: number) => {
        setTimeout(() => {
            console.log(`${value} async operation finished`);
        }, 10);
    };
    const ls = [];
    for (let i = 0; i < 10; i++) {
        ls.push(i);
    }
    ls.map(asyncOperation);
    setTimeout(() => {
        console.log('.');
    }, 1);
    console.log('map finished');
};
/* 
output:
map finished
0 async operation finished
1 async operation finished
2 async operation finished
3 async operation finished
4 async operation finished
5 async operation finished
6 async operation finished
7 async operation finished
8 async operation finished
9 async operation finished
*/ 
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值