JS - Promise使用详解(ES6中的Promise)

JavaScript -- ES6的Promise 本文系统讲解了Promise在前端异步编程中的应用。首先分析回调函数的缺点(嵌套地狱),重点介绍Promise的实现原理:通过返回Promise对象和.then()链式调用实现异步顺序执行,并说明传参和错误处理机制。同时介绍了ES7的async/await语法糖,可消除.then()嵌套。还详细解析了Promise.all()和Promise.any()等原型方法的使用场景,通过商品查询案例演示其实际应用。最后预告将分享手写Promise的实现过程,帮助开发者深入理解异步编程原理。 阅读详情

JS - Promise使用详解2(ES6中的Promise)

2015年6月,  ES2015(即  ECMAScript 6、 ES6) 正式发布。其中  Promise 被列为正式规范,成为  ES6 中最重要的特性之一。

1,then()方法

简单来讲, then 方法就是把原来的回调写法分离出来,在异步操作执行完后,用链式调用的方式执行回调函数。
而  Promise 的优势就在于这个链式调用。我们可以在  then 方法中继续写  Promise 对象并返回,然后继续调用  then 来进行回调操作。

(1)下面通过样例作为演示,我们定义做饭、吃饭、洗碗( cook、 eat、 wash)这三个方法,它们是层层依赖的关系,下一步的的操作需要使用上一部操作的结果。(这里使用  setTimeout 模拟异步操作)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//做饭
function  cook(){
     console.log( '开始做饭。' );
     var  p =  new  Promise( function (resolve, reject){         //做一些异步操作
         setTimeout( function (){
             console.log( '做饭完毕!' );
             resolve( '鸡蛋炒饭' );
         }, 1000);
     });
     return  p;
}
 
//吃饭
function  eat(data){
     console.log( '开始吃饭:'  + data);
     var  p =  new  Promise( function (resolve, reject){         //做一些异步操作
         setTimeout( function (){
             console.log( '吃饭完毕!' );
             resolve( '一块碗和一双筷子' );
         }, 2000);
     });
     return  p;
}
 
function  wash(data){
     console.log( '开始洗碗:'  + data);
     var  p =  new  Promise( function (resolve, reject){         //做一些异步操作
         setTimeout( function (){
             console.log( '洗碗完毕!' );
             resolve( '干净的碗筷' );
         }, 2000);
     });
     return  p;
}

(2)使用  then 链式调用这三个方法:
1
2
3
4
5
6
7
8
9
10
cook()
.then( function (data){
     return  eat(data);
})
.then( function (data){
     return  wash(data);
})
.then( function (data){
     console.log(data);
});

当然上面代码还可以简化成如下:
1
2
3
4
5
6
cook()
.then(eat)
.then(wash)
.then( function (data){
     console.log(data);
});

(3)运行结果如下:
原文:JS - Promise使用详解2(ES6中的Promise)

2,reject()方法

上面样例我们通过  resolve 方法把  Promise 的状态置为完成态( Resolved),这时  then 方法就能捕捉到变化,并执行“ 成功”情况的回调。
而  reject 方法就是把  Promise 的状态置为已失败( Rejected),这时  then 方法执行“ 失败”情况的回调( then 方法的第二参数)。

(1)下面同样使用一个样例做演示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//做饭
function  cook(){
     console.log( '开始做饭。' );
     var  p =  new  Promise( function (resolve, reject){         //做一些异步操作
         setTimeout( function (){
             console.log( '做饭失败!' );
             reject( '烧焦的米饭' );
         }, 1000);
     });
     return  p;
}
 
//吃饭
function  eat(data){
     console.log( '开始吃饭:'  + data);
     var  p =  new  Promise( function (resolve, reject){         //做一些异步操作
         setTimeout( function (){
             console.log( '吃饭完毕!' );
             resolve( '一块碗和一双筷子' );
         }, 2000);
     });
     return  p;
}
 
cook()
.then(eat,  function (data){
   console.log(data +  '没法吃!' );
})
运行结果如下:
原文:JS - Promise使用详解2(ES6中的Promise)

(2)如果我们只要处理失败的情况可以使用  then(null, ...),或是使用接下来要讲的  catch 方法。
1
2
3
4
cook()
.then( null ,  function (data){
   console.log(data +  '没法吃!' );
})

3,catch()方法

(1)它可以和  then 的第二个参数一样,用来指定  reject 的回调
1
2
3
4
5
cook()
.then(eat)
. catch ( function (data){
     console.log(data +  '没法吃!' );
});

(2)它的另一个作用是,当执行  resolve 的回调(也就是上面  then 中的第一个参数)时,如果抛出异常了(代码出错了),那么也不会报错卡死  js,而是会进到这个  catch 方法中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//做饭
function  cook(){
     console.log( '开始做饭。' );
     var  p =  new  Promise( function (resolve, reject){         //做一些异步操作
         setTimeout( function (){
             console.log( '做饭完毕!' );
             resolve( '鸡蛋炒饭' );
         }, 1000);
     });
     return  p;
}
 
//吃饭
function  eat(data){
     console.log( '开始吃饭:'  + data);
     var  p =  new  Promise( function (resolve, reject){         //做一些异步操作
         setTimeout( function (){
             console.log( '吃饭完毕!' );
             resolve( '一块碗和一双筷子' );
         }, 2000);
     });
     return  p;
}
 
cook()
.then( function (data){
     throw  new  Error( '米饭被打翻了!' );
     eat(data);
})
. catch ( function (data){
     console.log(data);
});
运行结果如下:
原文:JS - Promise使用详解2(ES6中的Promise)

这种错误的捕获是非常有用的,因为它能够帮助我们在开发中识别代码错误。比如,在一个  then() 方法内部的任意地方,我们做了一个  JSON.parse() 操作,如果  JSON 参数不合法那么它就会抛出一个同步错误。用回调的话该错误就会被吞噬掉,但是用  promises 我们可以轻松的在  catch() 方法里处理掉该错误。

(3)还可以添加多个  catch,实现更加精准的异常捕获。
1
2
3
4
5
6
7
8
9
10
11
somePromise.then( function () {
  return  a();
}). catch (TypeError,  function (e) {
  //If a is defined, will end up here because
  //it is a type error to reference property of undefined
}). catch (ReferenceError,  function (e) {
  //Will end up here if a wasn't defined at all
}). catch ( function (e) {
  //Generic catch-the rest, error wasn't TypeError nor
  //ReferenceError
});

4,all()方法

Promise 的  all 方法提供了并行执行异步操作的能力,并且在所有异步操作执行完后才执行回调。

(1)比如下面代码,两个个异步操作是并行执行的,等到它们都执行完后才会进到  then 里面。同时  all 会把所有异步操作的结果放进一个数组中传给  then。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//切菜
function  cutUp(){
     console.log( '开始切菜。' );
     var  p =  new  Promise( function (resolve, reject){         //做一些异步操作
         setTimeout( function (){
             console.log( '切菜完毕!' );
             resolve( '切好的菜' );
         }, 1000);
     });
     return  p;
}
 
//烧水
function  boil(){
     console.log( '开始烧水。' );
     var  p =  new  Promise( function (resolve, reject){         //做一些异步操作
         setTimeout( function (){
             console.log( '烧水完毕!' );
             resolve( '烧好的水' );
         }, 1000);
     });
     return  p;
}
 
Promise
.all([cutUp(), boil()])
.then( function (results){
     console.log( "准备工作完毕:" );
     console.log(results);
});

(2)运行结果如下:
原文:JS - Promise使用详解2(ES6中的Promise)

5,race()方法

race 按字面解释,就是赛跑的意思。 race 的用法与  all 一样,只不过  all 是等所有异步操作都执行完毕后才执行  then 回调。而  race 的话只要有一个异步操作执行完毕,就立刻执行  then 回调。
注意:其它没有执行完毕的异步操作仍然会继续执行,而不是停止。

(1)这里我们将上面样例的  all 改成  race
1
2
3
4
5
6
Promise
.race([cutUp(), boil()])
.then( function (results){
     console.log( "准备工作完毕:" );
     console.log(results);
});
原文:JS - Promise使用详解2(ES6中的Promise)

(2) race 使用场景很多。比如我们可以用  race 给某个异步请求设置超时时间,并且在超时后执行相应的操作。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//请求某个图片资源
function  requestImg(){
     var  p =  new  Promise( function (resolve, reject){
     var  img =  new  Image();
     img.onload =  function (){
        resolve(img);
     }
     img.src =  'xxxxxx' ;
     });
     return  p;
}
 
//延时函数,用于给请求计时
function  timeout(){
     var  p =  new  Promise( function (resolve, reject){
         setTimeout( function (){
             reject( '图片请求超时' );
         }, 5000);
     });
     return  p;
}
 
Promise
.race([requestImg(), timeout()])
.then( function (results){
     console.log(results);
})
. catch ( function (reason){
     console.log(reason);
});
上面代码  requestImg 函数异步请求一张图片, timeout 函数是一个延时  5 秒的异步操作。我们将它们一起放在  race 中赛跑。
  • 如果 5 秒内图片请求成功那么便进入 then 方法,执行正常的流程。
  • 如果 5 秒钟图片还未成功返回,那么则进入 catch,报“图片请求超时”的信息。
原文:JS - Promise使用详解2(ES6中的Promise)

原文出自: www.hangge.com   转载请保留原文链接: http://www.hangge.com/blog/cache/detail_1638.html
Javascript.9——ES6【Promise的async和await 使用】 好至此呢,咱们promise这一块东西就学完了啊,promise这个东西呢大家也体验到了,它并没有消除回调的,它回调是没有消除的,你看我们promise里边,【new Promise(…).then( ()=>{ } 】这里边是不是有回调,然后后边我们的then方法里边是不是一个回调函数对吧,Promise它其实没有消除回调,但它消除了什么呢,它有两个作用, 阅读详情

相关推荐

tcllib2.0 package - csv

tcl lib 的csv库

shin 859

【ES】笔记-Promise基本使用

/ alert('恭喜恭喜, 奖品为 10万 RMB 劳斯莱斯优惠券');'恭喜恭喜, 奖品为 10万 RMB 劳斯莱斯优惠券, 您的中奖数字为 '将回调函数的方法转化为promise函数的方法,使得代码更简洁。// 将 promise 对象的状态设置为 『成功』// 将 promise 对象的状态设置为 『失败』// //获取从1 - 100的一个随机数。// alert('再接再厉');// resolve 解决 函数类型的数据。//调用 then 方法。

德仔 1530

Zlib1.2.11源码编译(Win10+VS2019)

下载 下载网址: zlib Home Site 得到文件: 解压缩到“D:\SourceCodes\zlib-1.2.11” 使用CMake配置、生成并打开项目 将CMakeLists.txt拖入CMake,配置(Configure): 生成(Generate) 打开项目(Open Project),CMake调用VS2019打开项目 生成debug版本 构建项目ALL_BUILD。成功生成debug版本 在“D:\Sourc...

Alexabc3000的专栏 1893

ES6 Promise总结与归纳——看这一篇就够了

ES6 Promise的2个阶段,2个过程,3种状态详解

weixin_43936341的博客 565

2025华为OD面试手撕代码真题目录、八股文真题目录以及面试技巧

1. **华为OD面试技术面准备指南** 2. **华为OD面试技术面常见问题解答** 3. **华为OD面试技术面经验分享** 4. **华为OD面试技术面注意事项** 5. **华为OD面试技术面攻略** 6. **华为OD面试技术面模拟题目与解析** 7. **华为OD面试技术面知识点梳理** 8. **华为OD面试技术面常考**

算法大师! 3万+

UDS诊断服务基础详解之七-31服务

本节内容主要是讲解诊断服务中的31服务,包含31服务的使用场景,请求报文格式,响应报文格式,以及举例对31服务进行相关的说明

车载网络小D的博客 5629

ES6---promise详解及用法

一、什么是Promise Promise是ES6异步编程的一种解决方案(目前最先进的解决方案是async和await的搭配(ES8),但是它们是基于promise的),从语法上讲,Promise是一个对象或者说是构造函数,用来封装异步操作并可以获取其成功或失败的结果。 二、为什么要使用promise 最重要也是最主要的一个场景就是ajax和axios请求。通俗来说,由于网速的不同,可能你得到返回值的时间也是不同的,但是我们下一步要执行的代码依赖于上一次请求返回值,这个时候我们就需要等待,结果出来了.

前端与计算机相关知识的分享,博主的qq523235674 2万+

“华为杯”研究生数学建模竞赛2016年-【华为杯】A题:多无人机协同任务规划

题分别求解,保证了攻击方无人机滞留在防御方雷达有效探测范围内的时间总和最小,接着,通过提出巡检待命无人机的设想,型无人机携带炸弹的具体清单和攻击的目标清单),保证攻击方的无人机滞留防御方雷。在使用基于贪心算法的覆盖法时,覆盖的目标点中必须首先不含配备雷达站的目标点。步优化保证攻击方的无人机滞留防御方雷达有效探测范围内的时间总和最小,需首先。的“灵巧”炸弹,采用抛投方式对地攻击,即投放后炸弹以飞机投弹时的速度作抛物。运动,当炸弹接近目标后,可主动寻的攻击待打击的目标,因此炸弹落点位于目标中。

getusushu的博客 1036

JS - Promise使用详解2(ES6中的Promise)

2015年6月, ES2015(即 ECMAScript 6、ES6) 正式发布。其中 Promise 被列为正式规范,成为 ES6 中最重要的特性之一。 1,then()方法 简单来讲,then 方法就是把原来的回调写法分离出来,在异步操作执行完后,用链式调用的方式执行回调函数。 而 Promise 的优势就在于这个链式调用。我们可以在 then 方法中继续写 Promise 

Elvis技术小屋 896

【GeoDa实用技巧100例】024:geoda计算全局(局部)莫兰指数Moran‘s I,LISA聚类地图,显著性地图

【GeoDa实用技巧100例】024:geoda计算全局(局部)莫兰指数Moran's I,单变量莫兰指数,双变量莫兰指数计算,LISA聚类地图,显著性地图,Geoda双变量莫兰指数是一种强大的地理空间数据分析工具。

智慧空间实验室 6051

【电容/电感】电路板会“滋滋”的响,我们称它为啸叫

一、啸叫的起源 大部分硬件工程师应该都遇到过,PCBA上电后出现“滋滋滋”的叫声,其声响或大或小,或时有时无,或深沉或刺耳,或变化无常者皆有。该现象我们称为“啸叫”,一般分为电感啸叫和电容啸叫。

云轩阁 6万+

ES6---Promise对象

ES6---Promise对象一、Promise 的含义Promise对象两个特点二、Promise 基本用法三、用Promise对象实现的 Ajax 操作四、Promise异步加载图片五、Promise.prototype.then()---添加状态改变时的回调函数六、Promise.prototype.catch()---指定发生错误时的回调函数七、Promise.prototype.finally()八、Promise.all()---合并多个 Promise 实例九、Promise.race()-.

赵佳敏的博客 856

【PINN物理信息网络】基于PINN物理信息网络结合Wave 2D有限差分方法(python)

【PINN物理信息网络】基于PINN物理信息网络结合Wave 2D有限差分方法(python)

k8291121的博客 1818

JS ES6 Promise 之 Hello World

■前言最近学习VUE,涉及到了一些内容,都不了解,比如 Axios, Promise,所以,整理记录一下仅仅是一个【 简单 】的介绍,更多的内容,可以看看提供的文章链接,或是其他的资料。0.AxiosAxios,可以理解为ajax i/o system,这不是一种新技术,本质上还是对原生XMLHttpRequest的封装,可用于浏览器和nodejs的HTTP客户端,只不过它是基于Promise的,符合最新的ES规范。

sun0322 5219

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

一篇梳理清楚JavaScript ES6中的Promise

Promise 改变了 JavaScript 的异步编程方式,提供了更清晰的语义、更优雅的代码结构和更强大的错误处理能力。

cuijiying的博客 1235

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

JavaScript ES6到ES10语法 回调地狱与异步操作 Promise then

[toc](JavaScript ES6到ES10语法 回调地狱与异步操作 Promise then)resolve reject catch all race。

一个做过前端开发的产品经理,经历过睿智产品的折磨导致脱发之后,励志要翻身"农奴"把歌唱,一边打入敌人内部一边持续提升自己,为我们广大开发同胞谋福祉,坚决抵制睿智产品折磨我们码农兄弟! 1006

深度学习工具包 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")

ES6-Promise终极指南:如何快速掌握JavaScript异步编程利器 [特殊字符]

ES6-Promise是一个轻量级的JavaScript Promise库,专门为ES6标准的Promise提供polyfill支持。在前100个字内,ES6-Promise作为核心关键词,为开发者提供了处理异步操作的完整解决方案。这个库源自rsvp.js的精简版本,体积小巧却功能强大,是前端开发中不可或缺的异步编程工具。无论你是初学者还是资深开发者,掌握ES6-Promise都将极大提升你的编程

gitblog_00028的博客 538

js promise的用法_Javascript进阶篇ES6-Promise的使用

什么是PromisePromise是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最早提出和实现,ES6将其写进了语言标准,统一了用法,原生提供了Promise对象。 所谓Promise,简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果。从语法上说,Promise是一个对象,从它可以获取异步操作的消息。Promise提供统一的...

weixin_39933026的博客 267

es6-promise-polyfill 自己实现promise.js

https://github.com/lahmatiy/es6-promise-polyfill/blob/master/promise.js登录后复制 (function(global){ // // Check for native Promise and it has correct interfac...

weixin_30121389的博客 243

搞懂 ES6 JavaScript 中的 Promise

搞懂 ES6 JavaScript 中的 Promise前言正文callbackcallback 是什麼callback hellpromisepromise 是甚麼promise 語法promise 的鏈式調用promise 與異步任務結語參考 前言 首先,這篇博客不會太短,因為要理解 js 的 promise 並不是特別容易的一件事情,在我個人看來,它算是 ES6 的一大進步,但也是學習上的一大門檻。ES6 promise 改善了以往使用 callback 所會造成的 “callback hell”,且

weixin_46803507的博客 546

ES6新标准下JS异步编程Promise解读

ES5及以下,要实现复杂的异步编程,需要大量运用回调函数,而每个回调函数中的执行正确与否无法及时判断,让你只能猜测或分析找问题,这将造成大量无法理解的情况出现。 ES6新标准引入Promise对上述问题进行解决,它的核心思想,是将上一次函数执行返回一个Promise对象,明确指示代码是否成功执行,则你可以基于此成功与否判断,以链式编程方式将复杂嵌套回调函数转换为简单流程化式的形式完成目标任务。

m0_74157361的博客 1747

JS中的回调函数,以及ES6中通过promise处理回调

简要介绍:ES6中,可以通过promise来处理回调函数,回调函数经常用于异步操作中,间接来说,可以通过promise优化异步操作。1.什么是JS中的回调函数?回调函数是作为参数传递给另外一个函数,并且改回调函数在函数主题执行完后再执行。举例来说:function callback(m,n){ alert("我是回调函数,我在执行"); return m+n }function myFuncti

liwusen的博客 2万+

JS的Promise & ES6模块化 & Commonjs模块化 ✅

首先,JavaScript自始至终都是一门单线程语言。其次,“宏任务”、“微任务”、“事件循环”这些名词都是异步代码里面才有的概念。Q:requestAnimationFrame的执行时机是什么时候?A:在一轮事件循环中,微任务清空之后,下一帧渲染开始之前。

YUYUYU972的博客 1298

现代 JavaScript (ES6+) 入门到实战(五):告别回调地狱,Promise 完全入门

当你执行一个异步操作时,它不会立即给你结果,而是先给你一张“回执单”(即 Promise 对象)。原本横向发展的“金字塔”,现在变成了纵向发展的“流水线”。到目前为止,我们处理的都是同步代码——代码从上到下一行行执行,简单直接。Promise 的出现,是 JavaScript 异步编程史上的一座里程碑。Promise 最强大的地方在于,它将“回调地狱”拉平成了一条。的中文意思是“承诺”。是浏览器内置的、基于 Promise 的网络请求 API。当一个异步操作需要依赖另一个的结果时,灾难就降临了。

程序员阿超的博客 712

promise-utils:为JavaScript/TypeScript开发者提供的ES6 Promise工具库

promise-utils:为JavaScript/TypeScript开发者提供的ES6 Promise工具库 在JavaScript和TypeScript的世界里,处理异步操作常常需要依赖Promise对象。然而,原生Promise在某些复杂场景下的处理并不方便。今天,我们为您推荐一个开源项目——promise-utils,它为开发者提供了一系列Lodash风格的实用工具函数,让Promise...

gitblog_00907的博客 481

JS每日一题: 如何理解es6中的Promise?

20190123问: 如何理解es6中的Promise? 试题解析:考查对JS中同步异步的理解,及工作中常用的使用场景 参考回答 js是单线程的,也就是说一次只能完成一个任务,为了解决这个问题,js将任务的执行模式分为两种, 同步和异步, 在es5中我们处理异步只能通过的回调的方式进行处理,在多层异步中,回调会一层一层嵌套,也就是所谓的回调地狱,promise就是异步编程的一种解决方案 Pr...

weixin_34416649的博客 205
上一篇: react路由的使用方法以及通过路由如何传参传递私有属性--【基于最新版本的react-router-dom(4.2.2)】
下一篇: 有趣的新技能,css水平垂直居中的特种方式。
Keyboard_Handler
博客等级 码龄10年 0粉丝 10原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值