假如面试官要你手写一个promise

面试官问我Promise/A+规范,我直接手写了一个then方法给他看 本文详细解析了如何手写符合Promise/A+规范的Promise实现,重点讲解了then方法的复杂实现和Promise解决过程。通过代码示例展示了状态管理、异步执行、链式调用等核心机制,帮助开发者深入理解JavaScript异步编程原理,提升面试表现。 阅读详情

promise

在开发中,经常需要用到promise,promise具有很多特性,这一次将对promise特性进行总结,并从零写一个promise。

步骤一

  • Promise特点
    • 1,创建时需要传递一个函数,否则会报错
    • 2,会给传入的函数设置两个回调函数
    • 3,刚创建的Promise对象状态是pending
class MyPromise {
  constructor(handle) {
    // 3,刚创建的Promise对象状态是pending
    this.status = "pending";
    // 1,创建时需要传递一个函数,否则会报错
    if (!this._isFunction(handle)) {
      throw new Error("请传入一个函数");
    }
    // 2,会给传入的函数设置两个回调函数
    handle(this._resolve.bind(this), this._reject.bind(this))
  }
  _resolve() {

  }
  _reject() {

  }
  _isFunction(fn) {
    return typeof fn === "function";
  }
}

步骤二

  • Promise特点
    • 4,状态一旦发生改变就不可再次改变
    • 5,可以通过then来监听状态的改变
      • 5.1,如果创建监听时,状态已经改变,立即执行监听回调
      • 5.2,如果创建监听时,状态未改变,会等状态改变后执行
      • 5.3,同一promise对象可以添加多个then监听,状态改变时按照注册顺序依次执行
// 定义常量保存对象的状态
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

class MyPromise {
  constructor(handle) {
    // 3,刚创建的Promise对象状态是pending
    this.status = PENDING;
    // 成功回调的值
    this.value = undefined;
    // 失败回调的值
    this.reason = undefined;
    // 注册的成功回调
    this.onResolvedCallbacks = [];
    // 注册的失败回调
    this.onRejectedCallbacks = [];
    // 1,创建时需要传递一个函数,否则会报错
    if (!this._isFunction(handle)) {
      throw new Error("请传入一个函数");
    }
    // 2,会给传入的函数设置两个回调函数
    handle(this._resolve.bind(this), this._reject.bind(this))
  }
  _resolve(value) {
    // 4,状态一旦发生改变就不可再次改变
    if (this.status === PENDING) {
      this.status = FULFILLED;
      this.value = value;
      // 5.3,同一promise对象可以添加多个then监听,状态改变时按照注册顺序依次执行
      this.onResolvedCallbacks.forEach(fn => fn(this.value));
    }
  }
  _reject(reason) {
    // 4,状态一旦发生改变就不可再次改变
    if (this.status === PENDING) {
      this.status = REJECTED;
      this.reason = reason;
      // 5.3,同一promise对象可以添加多个then监听,状态改变时按照注册顺序依次执行
      this.onRejectedCallbacks.forEach(fn => fn(this.reason));
    }
  }
  then(onResolved, onRejected) {
    // 判断有没有传入成功的回调
    if (this._isFunction(onResolved)) {
      // 5.1,如果创建监听时,状态已经改变,立即执行监听回调
      if (this.status === FULFILLED) {
        onResolved(this.value);
      }
    }
    // 判断有没有传入失败的回调
    if (this._isFunction(onRejected)) {
      // 5.1,如果创建监听时,状态已经改变,立即执行监听回调
      if (this.status === REJECTED) {
        onRejected(this.reason);
      }
    }
    // 5.2,如果创建监听时,状态未改变,会等状态改变后执行
    if (this.status === PENDING) {
      if (this._isFunction(onResolved)) {
        this.onResolvedCallbacks.push(onResolved);
      }
      if (this._isFunction(onRejected)) {
        this.onRejectedCallbacks.push(onRejected);
      }
    }
  }
  _isFunction(fn) {
    return typeof fn === "function";
  }
}

详解then方法

  • 接收两个参数:成功回调,失败回调
  • 如果promise失败了,但是没有注册失败监听,就会报错
  • then方法每次执行完毕都会返回一个新的Promise对象
    • 如果then方法只有成功回调
      • 则它返回的promise的状态会继承当前promise的状态。
      • 如果当前promise的状态为成功:新promise的值为当前then的成功回调的返回值。
      • 如果当前promise的状态为失败:新的promise没有失败监听,则会报错
    • 如果then方法同时包含成功回调、失败回调
    • 则它返回的promise的状态都为成功,且值为成功或者失败回调的返回值。
  • 回调函数的返回值
    • 如果then方法的成功/失败回调返回的是promise对象
      • 则then方法返回的新的promise对象的状态由新promise的内部决定。
      • 且值为新promise的内resolve/reject函数传递的参数。
    • 如果then方法的成功/失败回调返回的是普通数据类型
      • 则then方法返回的新的promise对象的状态都为成功。
      • 且值为成功/失败回调的返回值,即都会传递给新的promise对象成功的回调。
    • 如果then方法的成功/失败回调没有返回值
      • 同返回普通数据类型
  • 失败回调函数
    • 可以捕获上一个promise对象的then方法中成功回调函数执行时的异常

参考 前端进阶面试题详细解答

then(onResolved, onRejected) {
    return new MyPromise((nextResolve, nextReject) => {
      // 1.判断有没有传入成功的回调
      if (this._isFunction(onResolved)) {
        // 2.判断当前的状态是否是成功状态
        if (this.status === FULFILLED) {
          try {
            // 拿到上一个promise成功回调执行的结果
            let result = onResolved(this.value);
            // console.log("result", result);
            // 判断执行的结果是否是一个promise对象
            if (result instanceof MyPromise) {
              result.then(nextResolve, nextReject);
            } else {
              // 将上一个promise成功回调执行的结果传递给下一个promise成功的回调
              nextResolve(result);
            }
          } catch (e) {
            nextReject(e);
          }
        }
      }
      // 1.判断有没有传入失败的回调
      // if(this._isFunction(onRejected)){
      try {
        // 2.判断当前的状态是否是失败状态
        if (this.status === REJECTED) {
          let result = onRejected(this.reason);
          if (result instanceof MyPromise) {
            result.then(nextResolve, nextReject);
          } else {
            nextResolve(result);
          }
        }
      } catch (e) {
        nextReject(e);
      }
      // }
      // 2.判断当前的状态是否是默认状态
      if (this.status === PENDING) {
        if (this._isFunction(onResolved)) {
          // this.onResolvedCallback = onResolved;
          this.onResolvedCallbacks.push(() => {
            try {
              let result = onResolved(this.value);
              if (result instanceof MyPromise) {
                result.then(nextResolve, nextReject);
              } else {
                nextResolve(result);
              }
            } catch (e) {
              nextReject(e);
            }
          });
        }
        // if(this._isFunction(onRejected)){
        // this.onRejectedCallback = onRejected;
        this.onRejectedCallbacks.push(() => {
          try {
            let result = onRejected(this.reason);
            if (result instanceof MyPromise) {
              result.then(nextResolve, nextReject);
            } else {
              nextResolve(result);
              nextReject();
            }
          } catch (e) {
            nextReject(e);
          }
        });
        // }
      }
    });
}

详解catch方法

  • 其实是then方法的失败回调函数的语法糖
  • 如果需要同时使用then和catch方法,必须使用链式编程,不然会报错
  • 可以捕获上一个promise对象的then方法中成功回调函数执行时的异常
catch(onRejected) {
    return this.then(undefined, onRejected);
}

为啥使用catch时最好使用链式编程

  • 因为then方法只有成功回调,所以p2的状态会继承p1
  • 又因为p2的状态为失败,且没有对p2进行失败监听,所以报错
let p1 = new Promise(function (resolve, reject) {
  // resolve();
  reject();
});
let p2 = p1.then(function () {
  console.log("成功");
});
p1.catch(function () {
  console.log("失败1");
});

Promise.all()

  • Promise.all(params)特点
    • 参数为一个数组,且数组元素为promise类型数据
    • 返回值为一个promise,
      • 如果所有promise都执行成功
        • 返回值为所有promise都成功时返回的结果的集合
      • 如果有一个promise执行失败了,则返回失败的promise
static all(list){
    return new MyPromise(function (resolve, reject) {
        let arr = [];
        let count = 0;
        for(let i = 0; i < list.length; i++){
            let p = list[i];
            p.then(function (value) {
                // arr.push(value); 注意不要这样写,会导致结果顺序不对
                arr[i] = value
                count++;
                if(list.length === count){
                    resolve(arr);
                }
            }).catch(function (e) {
                reject(e);
            });
        }
    });
}

Promise.race()

  • Promise.race(params)特点
    • 参数为一个数组,且数组元素为promise类型数据
    • 返回值为一个promise,且返回值为第一个成功或者失败的promise的值
static race(list){
    return new MyPromise(function (resolve, reject) {
        for(let p of list){
            p.then(function (value) {
                resolve(value);
            }).catch(function (e) {
                reject(e);
            });
        }
    })
}

数十个锂电池充放电电路,锂电池充放电芯片 关乎锂电池供电的产品,在锂电池上,需要三个电路系统:1,锂电池保护电路,2,锂电池充电电路,3,锂电池输出电路。 内容目录: 单节的锂电池保护电路单节为3.7V锂电池(也叫4.2V)和3.8V锂电池(也叫4.35V) 单节的锂电池充电电路即锂电池保护板 单节的锂电池输出电路锂电池转换稳压输出为:1.2V,3.3V,5V,12V等等 两节的锂电池保护电路两节串联7.4V锂电池(也叫8.4V) 两节的锂电池充电电路即两节锂电池保护板 两节... 阅读详情

相关推荐

FPGA高速接口Aurora8B/10B协议实战:从IP核配置到数据流优化

本文详细介绍了FPGA高速接口Aurora8B/10B协议的实战应用,从IP核配置到数据流优化的全流程。通过Aurora8B/10B协议,开发者可以在FPGA间实现高效的数据传输,适用于高速接口设计。文章涵盖了协议基础、IP核配置、AXI4-Stream接口实战技巧以及性能优化策略,帮助读者快速掌握这一关键技术。

weixin_29280657的博客 269

手写一个promise用法_面试官:“你能手写一个 Promise 吗”

关于手写 Promise,想必大家都十分熟悉。基本上现在不管是大厂还是小厂,手写 promise 已经成为了面试必考知识点。听说你还不太会?那么走着,带你从零开始解锁 Promise!常见 Promise 面试题首先,我们以常见的 Promise 面试题为切入点,我们看看面试官们都爱考什么:Promise 解决了什么问题?Promise 的业界实现都有哪些?Promise 常用的 API 有哪些?...

weixin_35846141的博客 1065

Win10系统VS2019+Cmake+qhull_8.0.0环境配置

1 qhull 1.1 简要介绍 qhull是一个强大的计算几何库,可以用于计算高维的convex hull, Delaunay triangulation, Voronoi diagram等。 1.2 依赖库 qhull不依赖其他库。 1.3 源码包下载 qhull源码地址:github:https://github.com/qhull/qhull.git 2 Cmake构建项目 2.1 路径 源代码路径:D:/ThirdParty/qhull/qhull_8.0.0构建项目路径:D:/Thi.

wangchenxue的博客 2492

面试官:请手写一个Promise

面试官:请手写一个Promise?(开门见山)我:既然说到Promise,那我肯定得先介绍一下JavaScript异步编程的发展史吧,这样就理解为啥Promise会出现以及Promise解决了什么问题了吧。阶段一:回调函数阶段二:事件发布/订阅模型...面试官:我不关心什么异步编程发展史(不耐烦),这年头谁都知道Promise是解决了回调地狱的问题,我关心的是你的编码能力,你直接,直接写!!!我:好吧!(其实手写代码才是我的强项,嘻嘻!因为promise在EventLoop。

web全栈开发的博客 222

PCB工艺-SI9000-模型选择

本文介绍了PCB设计中常用的阻抗计算模型,主要包括外层、内层和嵌入式三类共12种计算模型,涵盖单端/差分、共面等不同场景。针对阻抗计算中的关键参数,文章提供了经验值参考:表层走线厚度0.035mm(1.4mil),内层0.0152mm(0.6mil);并列出常见PP材料的介电常数(3.8-4.5)和成品厚度(3-7.5mil)。作者建议90%的设计问题可通过上述模型解决,层叠参数建议咨询PCB厂家获取。

weixin_50120208的博客 1385

Vivado实战:从零封装AXI-Lite接口的呼吸灯IP核

本文提供了一份详细的Vivado实战指南,手把手教你如何将Verilog编写的呼吸灯模块封装成带AXI-Lite接口的IP核。内容涵盖从创建IP框架、编写核心逻辑、连接AXI总线到在ZYNQ系统中调用并编写C程序进行软硬件协同测试的完整流程,是掌握FPGA软硬件协同设计的关键实践。

weixin_29233333的博客 598

面试官:你会手写一个promise吗?

之前面试过几个开发,问到他们,你会手写一个promise吗?他们都说不知道,我以为他们是没理解题目,于是,我补充一下,说一下promise的构造函数吧。但他们还是一脸懵逼,今天仔细想一想,还是出一个教程和回答模板吧 我们先来看一段代码 class my_promise { constructor(exector) { this.status = "pending" /...

zero_person_xianzi的博客 1万+

Cursor Cloud Agent:云原生编程工作流的底层重构

编程工作流正从本地计算范式转向云原生执行范式。Cloud Agent 本质是将代码理解、生成、执行与调试等核心能力下沉至隔离、可控、按需分配的云端虚拟机,通过 Firecracker 微虚拟机实现亚秒级启动,并依托上下文快照、环境镜像化和内核级沙箱保障一致性、算力弹性与数据安全。这一范式突破了传统本地 AI 编程助手在环境依赖、调试能力与企业合规上的根本局限,使 IDE 从编辑工具升维为分布式开发指挥中心。本文深入解析其运行机制与工程落地实践。

weixin_34354173的博客 337

面试官:能不能手写一个 Promise?

大家好,我是若川。最近组织了源码共读活动,感兴趣的可以点此加我微信ruochuan12进群参与,每周大家一起学习200行左右的源码,共同进步。已进行4个月了,很多小伙伴表示收获颇丰。以下...

u012384510的博客 227

YOLO模型轻量化实战:剪枝、量化与知识蒸馏三大技术落地详解

这篇文章结合我自己的实战经验,从原理、操作、效果、避坑四个方面,给大家讲清楚了YOLO模型轻量化的三大核心技术:剪枝、量化、知识蒸馏。先明确应用场景,再选择合适的技术组合,不要盲目追求极致压缩,要在“大小、速度、精度”之间找平衡。实战才是最好的学习方式——大家可以先拿自己的数据集试试剪枝和量化,感受一下效果,有问题可以在评论区留言。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 594

【国密】基于SM2的协同签名与协同解密方案

两方协同签名指客户端与服务端协同完成签名、验签操作,具体实现方案参考了信工所专利[3]。在业务应用中,两方或多方的协同签名一般采用门限签名方案可以用来构造。门限密码算法在多方协作的相关场景中应用十分广泛,可以实现数据联合授权、认证、密钥安全恢复、密钥安全交换等需求,在诸多分布式多方计算协议中均可见其身影。在上述两方协同签名方案中,最巧妙的地方在于签名值s分量的构造,通过一些列数学变换,得以恢复。以下从两方协同签名方案介绍入手,介绍门限密码在协同签名中的应用。解决上述问题的关键在于门限密码算法的巧妙构造。

听雨草堂 8391

angular promise请求_面试官:“你能手写一个 Promise 吗”

关于手写 Promise,想必大家都十分熟悉。基本上现在不管是大厂还是小厂,手写 promise 已经成为了面试必考知识点。听说你还不太会?那么走着,带你从零开始解锁 Promise!查看完整代码请戳:github.com/qiruohan/ar…常见 Promise 面试题首先,我们以常见的 Promise 面试题为切入点,我们看看面试官们都爱考什么:Promise 解决了什么问题?Promis...

weixin_39894255的博客 99

信捷PLC XD5系列运动控制(10轴)编程应用篇

项目PLC采用XD5-60T10-E,36DI 24DO 晶体管输出,支持10路脉冲输出功能。TMR指令定时器时基可以自己设定,这点比其他品牌PLC方便。ZRN指令我们需要上升沿指令触发。 5、变址寻址 该说不说这个变址寻址是真的强,比西门子指针、三菱的变址寄存器Z 、V都要更加灵活。 7、特殊寄存器:时钟 8、如何建立PLC通讯...............

RXXW_Dor的博客 1万+

当面试官让我手写一个Promise时,他在考察什么?

当面试官让你手写一个Promise时,表面上是考察你对异步编程的理解,实则是一场对JavaScript核心能力的深度检验。随着前端工程复杂度提升,Promise已成为现代JS开发的基石,能否徒手实现它,直接暴露开发者对事件循环、链式调用等关键概念的掌握程度。如何处理then方法的链式调用尤为关键,需要返回新Promise形成调用链,这考察了工厂模式和链式编程的实践能力。能完美实现Promise的开发者,通常具备将复杂规范转化为可维护代码的系统能力,这正是现代前端工程最需要的核心素质。

rqejih_139的博客 216

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

【手撕原理】面试官:来吧,手写一个简单版的 Promise

重新实现Promise.js class myPromise{ constructor(exc){ if(typeof exc !== 'function'){ throw new TypeError('this is not a function!') } this.initValue(); this.initBind(); exc(this.resolve,this.reject);

超逸の学习技术博客 1313

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

2024年前端最全面试官:请手写一个Promise(2),字节面试官级别

列举常用的ES6特性:箭头函数需要注意哪些地方?拓展:var方式定义的变量有什么样的bug?Set数据结构拓展:数组去重的方法箭头函数this的指向。手写ES6 class继承。简单描述一下微信小程序的相关文件类型?你是怎么封装微信小程序的数据请求?有哪些参数传值的方法?你使用过哪些方法,来提高微信小程序的应用速度?小程序和原生App哪个好?简述微信小程序原理?分析微信小程序的优劣势怎么解决小程序的异步请求问题?// …// 定义两个数组。

2401_84413092的博客 889

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

2024年Web前端最新面试官:请手写一个Promise(3),2024年最新字节跳动的面试问题

四轮技术面+一轮hr面结束,学习到了不少,面试也是一个学习检测自己的过程,面试前大概复习了 一周的时间,把以前的代码看了一下,字节跳动比较注重算法,面试前刷了下leetcode和剑指offer, 也刷了些在牛客网上的面经。大概就说这些了,写代码去了~祝大家都能收获大厂offer~开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】篇幅有限,仅展示部分内容// 默认执行executor函数,并传入resolve和reject函数})})

2401_84437170的博客 962

面试让手写Promise,不可取

如果在面试中让手写 Promise,这个难度是比较大的,除非在面试前做了很深的功课,否则很难写出来,即使写出来也漏洞百出。为啥难?我们不妨看一下 Promise/A+ 的规范,我截了一张图...

lefex的博客 696

面试精选之Promise

前端面试过程中,基本都会问到 Promise,如果你足够幸运,面试官问的比较浅,仅仅问 Promise 的使用方式,那么恭喜你。事实上,大多数人并没有那么幸运。所以,我们要准备好九浅一深的知识。不知道读者有没有想过,为什么那么多面试官都喜欢问Promise?可以思考一下哦~常见 Promise 面试题我们看一些 Promise 的常见面试问法,由浅至深。1、了解 Promise 吗?2、Promi...

weixin_40581617的博客 143
上一篇: 京东前端二面高频手写面试题(持续更新中)
下一篇: 从零手写react-router
helloworld1024fd
博客等级 码龄4年 245粉丝 243原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值