问题
请尝试理解并解释代码的输出情况,以及微任务队列的情况。
情况一
代码
new Promise((r, rj) => {
console.log('外p');
r();
}).then(() => {
console.log('外then1');
return new Promise(((r, rj) => {
console.log('内p');
r();
})).then(() => {
console.log('内then1');
new Promise((r, rj) => { r(); console.log('resolve!')});
}).then(() => {
console.log('内then2');
});
}).then(() => {
console.log('外then2');
}).then(() => {
console.log('外then3');
}).then(() => {
console.log('外then4');
});
运行结果
外p
外then1
内p
内then1
resolve!
内then2
外then2
外then3
外then4
情况二
代码
new Promise((r, rj) => {
console.log('外p');
r();
}).then(() => {
console.log('外then1');
return new Promise(((r, rj) => {
console.log('内p');
r();
})).then(() => {
console.log('内then1');
return new Promise((r, rj) => { r(); console.log('resolve!')});
}).then(() => {
console.log('内then2');
});
}).then(() => {
console.log('外then2');
}).then(() => {
console.log('外then3');
}).then(() => {
console.log('外then4');
});
运行结果
外p
外then1
内p
内then1
resolve!
内then2
外then2
外then3
外then4
情况三
代码
new Promise((r, rj) => {
console.log('外p');
r();
}).then(() => {
console.log('外then1');
new Promise(((r, rj) => {
console.log('内p');
r();
})).then(() => {
console.log('内then1');
new Promise((r, rj) => { r(); console.log('resolve!')});
}).then(() => {
console.log('内then2');
});
}).then(() => {
console.log('外then2');
}).then(() => {
console.log('外then3');
}).then(() => {
console.log('外then4');
});
运行结果
外p
外then1
内p
内then1
resolve!
外then2
外then3
外then4
内then2
情况四
代码
new Promise((r, rj) => {
console.log('外p');
r();
}).then(() => {
console.log('外then1');
new Promise(((r, rj) => {
console.log('内p');
r();
})).then(() => {
console.log('内then1');
new Promise((r, rj) => { r(); console.log('resolve!')});
}).then(() => {
console.log('内then2');
});
}).then(() => {
console.log('外then2');
}).then(() => {
console.log('外then3');
}).then(() => {
console.log('外then4');
});
运行结果
外p
外then1
内p
内then1
resolve!
外then2
内then2
外then3
外then4
Comments NOTHING