GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Home
  • Archives
  • ABOUT

This view

  • Original page
  • New address

GeezerVison is showing coderming.github.io — school - M's BLOG

  • Home
  • Archives
  • ABOUT
  • Categories
  • tech
  • school

浅析阿里2018秋招前端编程测验题

先上题

// 实现一个函数,传入一个promise数组。要求数组中的函数按顺序依次执行,最后函数的返回值是一个由数组元素中各个promise返回值组成的数组
const timeout = ms => new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve();
    }, ms);
});

const ajax1 = () => timeout(2000).then(() => {
    console.log('1');
    return 1;
});

const ajax2 = () => timeout(1000).then(() => {
    console.log('2');
    return 2;
});

const ajax3 = () => timeout(2000).then(() => {
    console.log('3');
    return 3;
});

const mergePromise = ajaxArray => {
  // 填写此处的代码
};

mergePromise([ajax1, ajax2, ajax3]).then(data => {
    console.log('done');
    console.log(data); // data 为 [1, 2, 3]
});

分析

可以看到这个题是考我们对于promise的理解,算是较为基础的题。
首先我们看到最后函数执行完成后是一个then方法。那么我们就可以知道,mergePromise函数的返回值是一个promise。那么什么东西执行后会返回一个promise呢?无非就两种:一种是promise自身,一种是async function。
其次,我们看到传入mergePromise函数的参数,是一个长度不定的数组。处理长度不定的数组的各个元素,无非就是循环或者类循环了。即forEach,for循环这些。
根据上面两点,我想到了用async function。

本人的解法

  return (async function() {
    let index = 0, length = ajaxArray.length, dataArr = []
    while(index !== length) {
      dataArr.push(await ajaxArray[index++]())
    } 
    return dataArr
  })()
2020/06/23 posted in  school

M's BLOG

keep active, keep motivate.
Email RSS

Categories

tech school

Recent Posts

  • 浅析 protobuf 编码解码的实现
  • Timing Attack的原理和实用库 cryptiles
  • 浅析阿里2018秋招前端编程测验题

Copyright © 2015 Powered by MWeb,  Theme used GitHub CSS.

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.