then的用法(then的用法详解,让你的代码更加简洁高效)

then方法是Promise对象最基础的方法之一,在JavaScript中十分常用。本文详细讲解then的用法,帮助你更好的使用它。

then方法的含义

then方法会返回一个Promise,在这个Promise中,可以注册回调函数,等待异步操作完成后执行。

then方法的语法

then方法有两个参数,第一个是成功时的回调函数,第二个是失败时的回调函数,我们可以只传其中之一。

promise.then(onFulfilled[, onRejected])

then方法的链式调用

由于then方法会返回一个Promise,我们可以将多个then方法连续调用起来,形成链式结构,使代码更加简洁易读。

promise.then(fn1).then(fn2).then(fn3)

then方法的返回值

then方法返回的是一个新的Promise对象,可以继续进行链式调用,同时也可以使用catch方法,捕获链中的错误。

then方法的嵌套调用

我们可以在一个then方法的回调中嵌套另一个Promise对象的then方法,来处理复杂的异步操作。

promise.then(function(res){ 
return new Promise(function(resolve, reject){
resolve(res 1)
})
}).then(function(res){
console.log(res) // 2
})

相关信息