Promise中then的简单使用

文章介绍了如何使用Promise处理异步操作,包括返回新的Promise实例,链式调用then方法以及返回对象包含then的情况。在每次调用test()时,都会创建一个新的Promise实例,且展示了在then中返回值如何影响后续链式调用。
摘要由CSDN通过智能技术生成

接收异步返回值

function test() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("hello world")
        }, 2000)
    })
}

test().then(res => {
    console.log(res); // hello
})

多次调用

多次调用拿到的都是新的promise实例的返回值

function test() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("hello world")
        }, 2000)
    })
}

test().then(res => {
    console.log(res); // hello world
})

test().then(res => {
    console.log(res); // // hello world
})

链式调用

本身具有返回值

他本身的返回值为promise对象,他会接收回调函数返回的值,然后把它包装成promise实例返回,所以他可以链式调用

test().then(res => {
    console.log(res); // hello world
}).then(res => {
    console.log(res); // undefined
    return "hello js"
}).then(res => {
    console.log(res); // hello js
})

返回一个promise

test().then(res => {
    console.log(res); // hello world
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("hello promise") 
        }, 2000)
    })
}).then(res => {
    console.log(res);// 打印完hello world 2s后,会打印 hello promise
})

返回一个对象,对象中有then

test().then(res => {
    console.log(res); // hello world
    return {
        then(resolve, reject) {
            resolve("hello then")
        }
    }
}).then(res => {
    console.log(res); // hello then
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值