Promise.prototype.then 还能返回值? --<Javascript 学习笔记 7>

Lemon1x
• 阅读 456

Javascript 学习笔记 7

ECMAScript 6 (2015) 中,同样发布了一个新的对象,它叫做 Promise 。但是我们今天不细讲它的语法,而是来看它的 then 方法的返回值。

new Promise((resolve, reject) => {
    resolve(1);
})
    .then(num => {
        console.log(num);
        return num * 2;
    })
    .then(num => {
        console.log(num);
        return num * 2;
    })
    .then(num => {
        console.log(num);
        return num * 2;
    });

/*
输出:
1
2
4
*/

可见, then 中如果返回一个值,那么这个值将作为下一个 then 的参数传递。

那么看看下面这段代码吧。

function make(num) {
    return new Promise((resolve, reject) => {
        resolve(num * 2);
    });
}

new Promise((resolve, reject) => {
    resolve(1);
})
    .then(num => {
        console.log(num);
        return make(num);
    })
    .then(num => {
        console.log(num);
        return make(num);
    })
    .then(num => {
        console.log(num);
        return make(num);
    });

/*
输出:
1
2
4
*/

竟然依旧像原来一样输出,但是按上次的逻辑根本说不通啊。

实际上,如果你返回了一个非 Promise 的值,那么 return 值会作为下一个 then 的参数,而整个 then 的返回值,是一个 solve(num * 2) 的 Promise 。

但是如果你自己返回了一个 Promise ,其实是把该 then 变成了你自己的 Promise (改自第二个例子):

    .then(num => {
        console.log(num);
        return make(num);
    }) // 变成了 make(num)
    .then(num => {
        console.log(num);
        return make(num);
    }) // 变成了 make(num)
    .then(num => {
        console.log(num);
        return make(num);
    });
点赞
收藏
评论区
推荐文章

暂无数据

Lemon1x
Lemon1x
Lv1
男 · 学生
初二的某个班长,目前为JS开发者。 知乎同名,Gitee: Lemonix,Github: Lemonix-xxx
文章
0
粉丝
0
获赞
0
热门文章

暂无数据