ES6-Promise

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

Promise

主要用于解决异步回调函数嵌套问题

一、基本使用

let promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        // 返回错误内容,注意会继续向下执行
        // reject('错误内容');

        resolve('执行结果');
    }, 2000);
});

promise.then(result => {
    // then中回调方法被resolve方法调用
    console.log(result);
}).catch(error => {
    // catch中回调被reject方法调用
    console.log(error);
});

二、异步函数同步执行

// 任务1
function p1() {
    return new Promise(((resolve, reject) => {
        setTimeout(() => {
            resolve('p1结果');
        }, 1000)
    }));
}

// 任务2
function p2() {
    return new Promise(((resolve, reject) => {
        setTimeout(() => {
            resolve('p2结果');
        }, 1000)
    }));
}

// 任务3
function p3() {
    return new Promise(((resolve, reject) => {
        setTimeout(() => {
            resolve('p3结果');
        }, 1000)
    }));
}

// 实现异步函数同步执行
p1().then(result => {
    console.log(result);
    return p2()
}).then(result => {
    console.log(result);
    return p3()
}).then(result => {
    console.log(result);
});
es6-promise.auto.min.js 立即下载

相关推荐

es6-promise.auto.js

To use via a CDN include this in your html: <!-- Automatically provides/replaces `Promise` if missing or broken. --> [removed][removed] [removed][removed] <!-- Minified version of `es6-promise-auto` below. --> [removed][removed] [removed][removed]

【JS】ES6-Promise

Promise 是异步编程的一种解决方案: 从语法上讲,promise是一个对象,从它可以获取异步操作的消息;从本意上讲,它是承诺,承诺它过一段时间会给你一个结果。 promise有三种状态:pending(等待态),fulfiled(成功态),rejected(失败态);状态一旦改变,就不会再变。创造promise实例后,它会立即执行。promise是用来解决两个问题的:回调地狱,代码难以维护, 常常第一个的函数的输出是第二个函数的输入这种现象,提高代码的可读性。promise可以支持多个并发的请求,获取

m0_50947589的博客 704

小程序用es6 promise

小程序引用es6 promise,亲测,请大家下载,放心使用,谢谢!

ES6的Promise详解

本篇文章主要介绍了ES6语法中的Promise对象的使用详解,promise对象是JS进阶学习中的重要知识点,如果本文对你有所帮助请三连支持博主,你的支持是我更新的动力,先赞后看养成习惯。以下是本篇文章正文内容。

程序员柒的博客 6086

[CARLA系列--01]CARLA 0.9.15 在Windows下的安装教程(一)

Carla是一款开源的自动驾驶仿真器,它基本可以用来帮助训练自动驾驶的所有模块,包括感知系统,Localization, 规划系统等等.Carla这个产品目前已经更新到了最新的0.9.15版本,目前遇到好多人在windows系统上如何安装可编辑版的Carla遇到了好多问题,所以针对在windows上的安装,推出此列教程.

汽车ECU自动化测试 4659

在VM虚拟机的MobaXterm下安装JDK17

本文介绍了在Linux系统下安装配置JDK17的完整步骤:1)从Oracle或OpenJDK官网下载Linux版JDK17压缩包;2)上传至/usr/local目录;3)解压安装包;4)通过编辑/etc/profile文件配置环境变量,添加JAVA_HOME和PATH路径;5)使用source命令使配置生效;6)通过javac -version验证安装是否成功。整个过程涵盖了从下载到环境配置的完整流程,确保Java开发环境正确设置。

qq_2937655951的博客 446

ES6 - Promise

Promise是JavaScript中处理异步操作的容器,具有三种状态(pending、fulfilled、rejected),状态一旦改变不可逆转。它通过.then()链式调用处理成功结果,.catch()捕获错误,.finally()执行最终操作。Promise.all()处理多个Promise实例,全部成功才返回结果;Promise.race()则取最先完成的实例结果。Promise.resolve()将对象转为Promise。优点是状态管理清晰,缺点是无法取消、错误需显式捕获。适用于异步流程控制,如

m0_64387122的博客 793

Allan方差读图分析IMU误差指标

Allan方差标定IMU参数实测分析

weixin_44927558的博客 3574

ES6之-优雅的Promise

简单的分析源码解析其构造,从原理出发理解Promise

王光迪的CSDN 8217

node运行项目-Network: unavailable-没有ip地址

vscode运行vue项目后发现Network: unavailable 是什么情况呢?可能有一下三种情况:1.多个网卡原因:打开网络共享中心,把多余的网络禁用掉,只留一个2.在中配置host及public3.系统环境变量问题。

JackieDYH的博客 7549

智能汽车嘚啵嘚 --- 智能座舱第七稿:智能座舱的升级OTA

智能汽车嘚啵嘚 --- 智能座舱第七稿:智能座舱的升级OTA

Soly_kun的博客 415

es6 promise详解

基本概念 Promise是一个构造函数,自己身上有all、reject、resolve这几个眼熟的方法,原型上有then、catch等同样很眼熟的方法。这么说用Promise new出来的对象肯定就有then、catch方法喽,没错。 那就new一个玩玩吧。 var p = new Promise(function(resolve, reject){ //做一些异步操作 setTimeout(function(){ console.log('执行完成');

qq_40096030的博客 1571

推免保研夏令营/预推免面试记录—北航网安

链接:https://pan.baidu.com/s/1vkP3EzbVrCc8a7wgQuUZgQ?链接:https://pan.baidu.com/s/1n4EFS2c9WLAfQn91CP4j2g?链接:https://pan.baidu.com/s/1VVNNSfcNDWjXhVhH3MtNjA?上面五个比例基本为:1:5:2:1:1。面试时间:当天上午面试,但是没面完,下午吃了饭之后又继续面试。--来自百度网盘超级会员V5的分享。--来自百度网盘超级会员V5的分享。

admin的博客 3017

JS ES6 Promise 之 Hello World

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

sun0322 5223

前端使用二开Thingsboard一、二、三事(三)-规则链

以项目实战为基础,逐步介绍前端在thingsboard系统二次开发中的一些注意事项以及一些thingsboard一些页面功能讲解,为前端人员开发使用thingsboard提供一种可靠思路,打造一个完美的物联网系统。

weixin_43163457的博客 867

里海NX二次开发3000例-专栏目录

UDO(User Defined Object)是“用户自定义对象”。应用非常广,可以用UDO创建自定义特征,也可以对NX原有的特征添加一些特殊信息,这些信息会保存在部件中,以后可以查询。还可以实时追踪NX对象,例如做3D包容盒线框自动追踪实体,做2D矩形框自动追踪图纸尺寸值,这些在下面的例子都有介绍。读者可以自己编译下面的例子,体会理解UDO的用法。------里海 20230512序号内容​链接01使用UDO在所有实体上设置更新回调​链接02使用UDO生成跟踪实体的线框​链接03删除UDO​链接。

王牌飞行员_里海的博客 7736

ES6之Promise

ES5中实现异步的常见方式不外乎以下几种: 回调函数 事件驱动 自定义事件(根本上原理同事件驱动相同) 而ES6中的Promise的出现就使得异步变得非常简单。promise中的异步是这样的: 每当我需要执行一次异步操作的时候,我都需要new一个promise对象 每一个异步操作的Promise对象都需要设定一个成功执行的条件和成功的回调、一个失败的条件和失败的回调 Promise对象可通过...

EmotionComputer 254

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

ES6中Promise用法详解_es6中promise的用法

Promise.race的返回结果为一个Prmise实例,只不过这个实例只能是最先执行resolve的那个promise。有的时候有这样的需求,后面的ajax请求依赖前面的ajax请求必须按照顺序调动如何实现呢?注意:Promise.race的参数为一个数组,数组每一项都是promise实例对象。前面的回调是一种解决方案,但是想避免回调地狱的写法用promise实现顺序调用呢?resolve执行后返回promise的成功状态,Promise 来了,用promise怎么实现呢?

2401_87196407的博客 1268

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

Statistics and Machine Learning Toolbox

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

分析ES6Promise

简版ES6语法 function _Promise(...args) { this.status = "pending"; this.msg = ""; const process = args[0]; process( (...args) => { this.status = "resolve"; this.msg = args[0]; ...

coderMozart的博客 321

深度学习工具包 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 对象

ES6 Promise 对象

m0_52913477的博客 1416

Es6 Promise 实现

// promise 状态 const PENDING = 'pending'; const FULFILLED = 'fulfilled'; const REJECTED = 'rejected'; const isFn = fn => typeof fn === 'function'; class Promise { constructor(resolver) { if ...

weixin_34255793的博客 142

es6 Promise

es6 PromisePromise的设计初衷Promise含义Promise状态Promise特点Promise缺点Promise基本用法then()catch()finally()Promise.all()Promise.race() Promise的设计初衷 我们日常开发中,经常需要用到ajax请求数据,拿到数据后,再进行一些处理。 可有一次,你需要用ajax进行多次请求,而且,每次请求都依赖上一次请求返回的数据来作为参数,然后继续发出请求 ——>然后你把代码写的稀碎: $.ajax({

Hassan的小博客! 530

详解ES6的Promise

异步操作处理:Promise用于处理需要等待时间较长的操作,如网络请求、文件读取等。通过Promise可以更清晰地表达异步操作的执行顺序和结果处理。状态:Promise有三种状态:pending(进行中)、fulfilled(已完成)和rejected(已失败)。初始状态为pending,当操作成功完成时,状态变为fulfilled,如果发生错误,状态则变为rejected。then()方法:Promise对象的then()方法用于指定操作成功或失败时的回调函数。

m0_71966801的博客 1250

ES6——17. Promise对象

到了那个时候,Promise 的运行已经结束了,所以这个错误是在 Promise 函数体外抛出的,会冒泡到最外层,成了未捕获的错误。方法接受一个数组作为参数,数组的每个成员都是一个 Promise 对象,并返回一个新的 Promise 对象。这就是说,Promise 内部的错误不会影响到 Promise 外部的代码,通俗的说法就是“Promise 会吃掉错误”。事件的监听函数有两个参数,第一个是错误对象,第二个是报错的 Promise 实例,它可以用来了解发生错误的环境信息。方法,依次指定了两个回调函数。

chtazycdf的博客 1708

说说es6 promise async await 以及 promise A+规范的了解

Promise是 JavaScript 中用于处理异步操作的一种方式,它表示一个异步操作的最终完成(或失败)及其结果值的表示。Promise是 ES6 引入的,它通过链式调用来处理回调函数,避免了“回调地狱”的问题。async和await是 ES2017(ES8)引入的用于简化处理异步操作的语法糖。它们是基于Promise的,但使用起来更加简洁和直观。async:标记一个函数为异步函数,返回一个Promise对象。await:用于等待一个Promise对象的完成,await后面必须跟一个Promise。

HHX_01的博客 1182
上一篇: Windows 端口占用
下一篇: MacOS常用设置
yimtcode
博客等级 码龄7年 205粉丝 140原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yimtcode

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址