🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[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)\] ```