Promise实践

var doSomething = function() {
return new Promise((resolve, reject) => {
resolve('返回值');
});
};let doSomethingElse = function() {
return '新的值';
}doSomething().then(function () {
return doSomethingElse();
}).then(resp => {
console.warn(resp);
console.warn('1 =========<');
});doSomething().then(function () {
doSomethingElse();
}).then(resp => {
console.warn(resp);
console.warn('2 =========<');
});doSomething().then(doSomethingElse()).then(resp => {
console.warn(resp);
console.warn('3 =========<');
});doSomething().then(doSomethingElse).then(resp => {
console.warn(resp);
console.warn('4 =========<');
});

  

Promise.prototype.then

当Promise中的状态(pending ---> resolved or rejected)发生变化时才会执行then方法。

  • 调用then返回的依旧是一个Promise实例 ( 所以才可以链式调用... )
new Promise((res, rej)=> {res('a');
}).then(val=> {return 'b';
});// 等同于
new Promise((res, rej)=> {res('a');
}).then(val=> {return new Promise((res, rej)=> {res('b');});
});
  • then中的回调总会异步执行
new Promise((res, rej)=> {console.log('a');res('');
}).then(()=> {console.log('b');
});
console.log('c');
// a c b
  • 如果你不在Promise的参数函数中调用resolve或者reject那么then方法永远不会被触发
new Promise((res, rej)=> {console.log('a'); 
}).then(()=> {console.log('b');
});
console.log('c'); 
// a c

  

Promise.resolve()

除了通过new Promise()的方式,我们还有两种创建Promise对象的方法,Promise.resolve()相当于创建了一个立即resolve的对象。如下两段代码作用相同:

Promise.resolve('a');new Promise((res, rej)=> {res('a');
});

  

当然根据传入的参数不同,Promise.resolve()也会做出不同的操作。

  • 参数是一个 Promise 实例

如果参数是 Promise 实例,那么Promise.resolve将不做任何修改、原封不动地返回这个实例。

  • 参数是一个thenable对象

thenable对象指的是具有then方法的对象,比如下面这个对象。

let thenable = {then: function(resolve, reject) {resolve(42);}
};

  

Promise.resolve方法会将这个对象转为 Promise对象,然后就立即执行thenable对象的then方法。

  • 参数不是具有then方法的对象,或根本就不是对象

如果参数是一个原始值,或者是一个不具有then方法的对象,则Promise.resolve方法返回一个新的 Promise 对象,状态为resolved。

  • 不带有任何参数

Promise.resolve方法允许调用时不带参数,直接返回一个resolved状态的 Promise 对象。

class Man {constructor(name) {this.name = name;this.sayName();this.rope = Promise.resolve();  // 定义全局Promise作链式调用}sayName() {console.log(`hello, ${this.name}`);}sleep(time) {this.rope = this.rope.then(()=> {return new Promise((res, rej)=> {setTimeout(()=> {res();}, time*1000);});});return this;}eat(food) {this.rope = this.rope.then(()=> {console.log(`${this.name} eat ${food}`); });return this;}
}new Man('lan').sleep(3).eat('apple').sleep(5).eat('banana');

  

class Man1345 {constructor(name) {this.name = name;this.sayName(); }sayName() {console.log(`hello, ${this.name}`);}sleep(time) { this.rope = new Promise((res, rej)=> {setTimeout(()=> {res();}, time*1000);}); return this;}eat(food) {this.rope = this.rope.then(()=> { console.log(`${this.name} eat ${food}`);  });return this;}
}new Man('lan').sleep(3).eat('apple').sleep(5).eat('banana');

  

// 第一段正确的代码的执行为
var p1 = new Promise().then('停顿3s').then('打印食物').then('停顿5s').then('打印食物');// 第二段代码的执行行为,p1、p2异步并行执行
var p1 = new Promise().then('停顿3s').then('打印食物');
var p2 = new Promise().then('停顿5s').then('打印食物');

  

Promise对象在创建即执行(new--关键字)
then(拿前面异步的返回值)

 

 

转载于:https://www.cnblogs.com/smzd/p/8861469.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/249902.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

JsonBuilder初出茅庐

互联网这股东风不久前刮到了甘凉国&#xff0c;国王老甘独具慧眼&#xff0c;想赶紧趁着东风未停大力发展移动互联网&#xff0c;因为他笃信布斯雷的理论&#xff1a;“站在风口上&#xff0c;猪都能飞起来”。无奈地方偏僻落后&#xff0c;国内无可用之才啊。老甘一筹莫展的低…

Nexus介绍

转自&#xff1a;https://www.cnblogs.com/wincai/p/5599282.html 开始在使用Maven时&#xff0c;总是会听到nexus这个词&#xff0c;一会儿maven&#xff0c;一会儿nexus&#xff0c;当时很是困惑&#xff0c;nexus是什么呢&#xff0c;为什么它总是和maven一起被提到呢&#…

vue-cli 打包

一项目打包 1 打包的配置在 build/webpack.base.conf.js文件下 常量config在vue/config/index.js 文件下配置&#xff0c;__dirname是定义在项目的全局变量&#xff0c;是当前文件所在项目的文件夹的绝对路径。 2 需要修改vue/config/index.js 文件下的将build对象下的assets…

乘风破浪:LeetCode真题_010_Regular Expression Matching

乘风破浪&#xff1a;LeetCode真题_010_Regular Expression Matching 一、前言 关于正则表达式我们使用得非常多&#xff0c;但是如果让我们自己写一个&#xff0c;却是有非常大的困难的&#xff0c;我们可能想到状态机&#xff0c;确定&#xff0c;非确定状态机确实是一种解决…

vue项目工程中npm run dev 到底做了什么

npm install 安装了webpack框架中package.json中所需要的依赖 2.安装完成之后&#xff0c;需要启动整个项目运行&#xff0c;npm run 其实执行了package.json中的script脚本&#xff0c;npm run dev的执行如下 3.底层相当执行webpack-dev-server --inline --progress --confi…

bat等大公司常考java多线程面试题

1、说说进程,线程,协程之间的区别 简而言之,进程是程序运行和资源分配的基本单位,一个程序至少有一个进程,一个进程至少有一个线程.进程在执行过程中拥有独立的内存单元,而多个线程共享内存资源,减少切换次数,从而效率更高.线程是进程的一个实体,是cpu调度和分派的基本单位,是比…

offset系列,client系列,scroll系列回顾

一 scroll系列属性 ——滚动1 scrollHeight/scrollWidth 标签内部实际内容的高度/宽度ele.scrollHeight 有两种情况&#xff0c;当内容超出盒子范围后&#xff0c;返回的是内容的高度&#xff0c;包括padding&#xff0c;从顶部内侧到内容的最外部分。当内容不超出盒子范围…

项目开发中的自我总结

最近忙的要死,因为新开发了两个项目.现在已经测试完毕了,准备部署到线上了. 然后不能白忙活吧,忙活完也得写点总结和经验吧,以后也有个记录. 1.一个bootstrapjquerylayuilaravel 5.4开发的一个后台系统 比较朴素 2.一个前后端分离的vuelaravel 5.4 开发的商家系统 我只负责后端…

数组黑科技(偏性能方面)未完待更新...

数组去重最优解&#xff1a;Array.prototype.unique function () {var tmp new Map();return this.filter(item > {return !tmp.has(item) && tmp.set(item,1);})}搭配使用 Array.from(foo); // ["f", "o", "o"]let s new Set([f…

控制台添加log4net

1.添加nuget包 log4net 2.app.config配置 <?xml version"1.0" encoding"utf-8"?> <configuration> <configSections><section name"log4net" type"log4net.Config.Log4NetConfigurationSectionHandler, log4net&quo…

touchWX 自定义组件以及传值

创建如图文件 index.wxc: <template><view class"wx-test" bindtap"handleTap">{{ msg }}{{dataIndex}}</view> </template> <script>export default {properties: {dataIndex: {type: String,value: default value,}},data…

vue 初始框架

VueJs讲解初始框架 一、启动项目 第一步&#xff1a;cmd进入项目文件里&#xff0c;运行npm run dev 启动项目 这里说明启动端口号是8080 第二步&#xff1a;往页面输入&#xff1a;localhost:8080 二、解析渲染步骤 先看整体框架样式和index.html&#xff1a; 从上面我…

Country Road Aizu - 2104

题目链接&#xff1a; https://vjudge.net/problem/Aizu-2104 题解&#xff1a; 咋说啊&#xff0c;一言难尽&#xff0c;花了半小时写出来的&#xff0c;卡了十分钟才恍然大明白是排序。 具体就是让每个村子都通上电&#xff0c;变压器在的村子&#xff0c;与变压器连线点线长…

IdentityServer4【QuickStart】之使用asp.net core Identity

使用asp.net core Identity IdentityServer灵活的设计中有一部分是可以将你的用户和他们的数据保存到数据库中的。如果你以一个新的用户数据库开始&#xff0c;那么&#xff0c;asp.net core Identity是一个选择。这个示例演示了如何在IdentityServer中使用asp.net core Ientit…

vue demo1

1.开发工具 试过sublime&#xff0c;现在转战vscode&#xff0c;觉得很顺手&#xff0c;总之啥工具习惯就好。 vscode用着不错的插件&#xff0c;推荐安装。 2.项目目录介绍 vue-cli生成的项目目录有点多&#xff0c;初看有点懵&#xff0c;梳理一下会好很多。 ├── ind…

CentOS下防御或减轻DDoS攻击方法(转)

查看攻击IP 首先使用以下代码&#xff0c;找出攻击者IP netstat -ntu | awk {print $5} | cut -d: -f1 | sort | uniq -c | sort -n 将会得出类似如下的结果&#xff1a; 1 114.226.9.132 1 174.129.237.157 1 58.60.118.142 1 Address 1 servers) 2 118.26.131.78 3 123.125.1…

vscode - 添加背景图片

首先&#xff0c;CtrlShiftP安装backround &#xff0c; 而后重启vscode会有默认的背景图片 修改背景图&#xff0c;可自定义三张 具体请看gif图 最开始时&#xff0c;发现png根本不是全透明&#xff0c;用ps处理了一下&#xff08;下列所有操作均字母组合&#xff09; 1.1 Ctr…

关于Vue.use()详解

问题 相信很多人在用Vue使用别人的组件时&#xff0c;会用到 Vue.use() 。例如&#xff1a;Vue.use(VueRouter)、Vue.use(MintUI)。但是用 axios时&#xff0c;就不需要用 Vue.use(axios)&#xff0c;就能直接使用。那这是为什么呐&#xff1f; 答案 因为 axios 没有 install。…

分布式工具的一次小升级⏫

前言 之前在做 秒杀架构实践 时有提到对 distributed-redis-tool 的一次小升级&#xff0c;但是没有细说。 其实主要原因是&#xff1a; 秒杀时我做压测&#xff1a;由于集成了这个限流组件&#xff0c;并发又比较大&#xff0c;所以导致连接、断开 Redis 非常频繁。 最终导致获…

浅谈vue $mount()

Vue 的$mount()为手动挂载&#xff0c;在项目中可用于延时挂载&#xff08;例如在挂载之前要进行一些其他操作、判断等&#xff09;&#xff0c;之后要手动挂载上。new Vue时&#xff0c;el和$mount并没有本质上的不同。 具体见代码&#xff1a; 顺便附上vue渲染机制流程图&a…