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.pswp.cn/news/249902.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/249902.shtml
英文地址,請注明出處:http://en.pswp.cn/news/249902.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

JsonBuilder初出茅廬

互聯網這股東風不久前刮到了甘涼國&#xff0c;國王老甘獨具慧眼&#xff0c;想趕緊趁著東風未停大力發展移動互聯網&#xff0c;因為他篤信布斯雷的理論&#xff1a;“站在風口上&#xff0c;豬都能飛起來”。無奈地方偏僻落后&#xff0c;國內無可用之才啊。老甘一籌莫展的低…

vue-cli 打包部署

1、一般打包 &#xff1a;直接 npm run build。&#xff08;webpack的文件&#xff0c;根據不同的命令&#xff0c;執行不同的代碼的&#xff09; 注&#xff1a;這種打包的靜態文件&#xff0c;只能放在web服務器中的根目錄下才能運行。 2、在服務器中 非根目錄下 運行的 打包…

EXCEL怎么打20位以上的數字?

EXCEL怎么打20位以上的數字&#xff1f; 轉載于:https://www.cnblogs.com/macT/p/10208794.html

vue render函數

Vue中的Render渲染函數 VUE一般使用template來創建HTML&#xff0c;然后在有的時候&#xff0c;我們需要使用javascript來創建html&#xff0c;這時候我們需要使用render函數。比如如下我想要實現如下html&#xff1a; <div id"container"><h1><a hre…

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;非確定狀態機確實是一種解決…

python——獲取數據類型

在python中&#xff0c;可使用type()和isinstance()內置函數獲取數據類型 如&#xff1a; &#xff08;1&#xff09;type()的使用方法&#xff1a;    >>> a 230 >>> type(a) <class str> >>> a 230 …

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…

JavaScript回顧與學習——條件語句

一、if...else // if elsevar age 16;if(0 < age && age < 6){console.log("兒童");}else if(6 < age && age < 14){console.log("少年");}else if(14 < age && age < 35){console.log("青年");}els…

bat等大公司常考java多線程面試題

1、說說進程,線程,協程之間的區別 簡而言之,進程是程序運行和資源分配的基本單位,一個程序至少有一個進程,一個進程至少有一個線程.進程在執行過程中擁有獨立的內存單元,而多個線程共享內存資源,減少切換次數,從而效率更高.線程是進程的一個實體,是cpu調度和分派的基本單位,是比…

webpack.config.js和package.json

webpack.config.js 是webpakc的配置文件&#xff0c;webpack是當今很火的一個打包工具 使用webpack.config.js在你的項目里 可以對你的項目進行模塊化打包&#xff0c;并且也可使組件按需加載&#xff0c;還可將圖片變成base64格式減少網絡請求。 而package.json 是指你項目的…

七牛云圖片加載優化

?imageView2/2/w/80https://developer.qiniu.com/dora/manual/1279/basic-processing-images-imageview2 ?imageView2/1/w/80/h/80會裁剪 ?imageView2/3/w/80/h/80不會裁剪 轉載于:https://www.cnblogs.com/smzd/p/9025393.html

org.apache.maven.archiver.mavenarchiver.getmanifest怎么解決

原因就是你的maven的配置文件不是最新的 1.help ->Install New Software -> add ->https://otto.takari.io/content/sites/m2e.extras/m2eclipse-mavenarchiver/0.17.2/N/LATEST 或者&#xff08;更新于2018年4月18日17:07:53&#xff09; http://repo1.maven.org/mav…

npm中package.json詳解

通常我們使用npm init命令來創建一個npm程序時&#xff0c;會自動生成一個package.json文件。package.json文件會描述這個NPM包的所有相關信息&#xff0c;包括作者、簡介、包依賴、構建等信息&#xff0c;格式是嚴格的JSON格式。 常用命令 npm i --save packageName 安裝依賴…

offset系列,client系列,scroll系列回顧

一 scroll系列屬性 ——滾動1 scrollHeight/scrollWidth 標簽內部實際內容的高度/寬度ele.scrollHeight 有兩種情況&#xff0c;當內容超出盒子范圍后&#xff0c;返回的是內容的高度&#xff0c;包括padding&#xff0c;從頂部內側到內容的最外部分。當內容不超出盒子范圍…

項目開發中的自我總結

最近忙的要死,因為新開發了兩個項目.現在已經測試完畢了,準備部署到線上了. 然后不能白忙活吧,忙活完也得寫點總結和經驗吧,以后也有個記錄. 1.一個bootstrapjquerylayuilaravel 5.4開發的一個后臺系統 比較樸素 2.一個前后端分離的vuelaravel 5.4 開發的商家系統 我只負責后端…

webpack.config.js 參數詳解

webpack.config.js文件通常放在項目的根目錄中&#xff0c;它本身也是一個標準的Commonjs規范的模塊。 var webpack require(webpack); module.exports {entry: [webpack/hot/only-dev-server,./js/app.js],output: {path: ./build,filename: bundle.js},module: {loaders: …

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

數組去重最優解&#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…