ES6 - 对Promise的处理顺序感到困惑

时间:2015-09-17 21:29:18

标签: ecmascript-6 es6-promise

我有这段代码:

let p1 = new Promise(function (resolve, reject) {
    setTimeout(function () {
        resolve({dogs: ['Fido', 'Spot']});
    }, 2000);
});

p1.then(function (val) {
    console.log('first then');
    console.dir(val);
    return _.extend(val, {cats: ['Fluffy', 'Whiskers']});
}).then(function (val) {
    console.log('second then');
    console.dir(val);
});

意外的控制台输出显示:

enter image description here

我不明白cats在实际附加到对象之前如何成为值的一部分。第二个then中打印的结果对我来说很有意义。我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

您正在将cats属性添加到已记录的同一对象中。

正如i图标告诉您的那样,控制台仅在您实际展开对象时才读取对象的属性。

答案 1 :(得分:0)

据我所知,ES6 Promises在console.log中存在一个错误。它会在记录对象的值之前等待几秒钟,这就是它包含猫的原因。如果我记得很清楚,这个bug就发生在firefox中。我不知道其他浏览器的行为方式。

相关问题