ES6 - 对 Promise 的处理顺序感到困惑
ES6 - Confused about processing order of 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);
});
意外的控制台输出显示:
我不明白 cats
在实际附加到对象之前怎么可能成为值的一部分。不过,第二个 then
中打印的结果对我来说很有意义。我错过了什么吗?
您正在将 cats
属性 添加到您已经记录的同一个对象。
正如 i
图标告诉您的那样,控制台仅在您实际展开对象时读取对象的属性。
据我所知,ES6 Promises 在 console.log 中存在一个错误。它在记录您的对象的值之前等待几秒钟,这就是它包含猫的原因。如果我没记错的话,这个错误发生在 firefox 中。我不知道其他浏览器的表现如何。
我有这个代码:
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);
});
意外的控制台输出显示:
我不明白 cats
在实际附加到对象之前怎么可能成为值的一部分。不过,第二个 then
中打印的结果对我来说很有意义。我错过了什么吗?
您正在将 cats
属性 添加到您已经记录的同一个对象。
正如 i
图标告诉您的那样,控制台仅在您实际展开对象时读取对象的属性。
据我所知,ES6 Promises 在 console.log 中存在一个错误。它在记录您的对象的值之前等待几秒钟,这就是它包含猫的原因。如果我没记错的话,这个错误发生在 firefox 中。我不知道其他浏览器的表现如何。