[TOC]
## .then( )
`then( )*`方法返回一個??[`Promise`](https://developer.mozilla.org/zh-CN/docs/Web/API/Promise "此頁面仍未被本地化, 期待您的翻譯!")。它最多需要有兩個參數:Promise 的成功和失敗情況的回調函數。
具體文檔>>>[.then()]([https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global\_Objects/Promise/then](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/then))
使用方法
~~~js
let p1 = new Promise(function(resolve, reject) {
resolve("Success!");
// or
// reject ("Error!");
});
p1.then(function(value) {
console.log(value); // Success!
}, function(reason) {
console.log(reason); // Error!
});
~~~
鏈式調用
then 方法返回一個Promise?對象,其允許方法鏈。
你可以傳遞一個 lambda 給 then 并且如果它返回一個 promise,一個等價的 Promise 將暴露給后續的方法鏈。下面的代碼片段使用 setTimout 函數來模擬異步代碼操作。
~~~js
Promise.resolve("foo")
// 1. 接收 "foo" 并與 "bar" 拼接,并將其結果做為下一個resolve返回。
.then(function(string) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
string += 'bar';
resolve(string);
}, 1);
});
})
// 2. 接收 "foobar", 放入一個異步函數中處理該字符串
// 并將其打印到控制臺中, 但是不將處理后的字符串返回到下一個。
.then(function(string) {
setTimeout(function() {
string += 'baz';
console.log(string);
}, 1)
return string;
})
// 3. 打印本節中代碼將如何運行的幫助消息,
// 字符串實際上是由上一個回調函數之前的那塊異步代碼處理的。
.then(function(string) {
console.log("Last Then: oops... didn't bother to instantiate and return " +
"a promise in the prior then so the sequence may be a bit " +
"surprising");
// 注意 `string` 這時不會存在 'baz'。
// 因為這是發生在我們通過setTimeout模擬的異步函數中。
console.log(string);
});
~~~
```
// 數組去重 \[...new Set(arr)\]
```
- 前言
- 你真的懂This嗎?
- 對象和對象構造函數
- 工廠功能和模塊模式
- API的使用
- async and await
- 關于async的很棒的一篇文章
- 掘金:關于forEach,map,fiter循環操作
- Node.js 實例與基礎
- 原創: Express 學習使用筆記
- 零碎知識點方法
- 關于滾動吸頂的方法
- Vue學習筆記
- Vue向導
- vuex是啥?
- vue代碼風格指南
- 關于vue的初體驗
- 超詳細解毒Vue
- Vue實例
- 模版語言
- 組件基礎
- 條件渲染、列表渲染、Class與style綁定
- Todolist的制作超詳細
- vue-router
- Vue基礎2.0x 筆記
- 搭建vuepress
- JavaScript之ES6
- 箭頭函數
- 這就是This