-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Promise 执行顺序 #42
Labels
Comments
Promise.resolve(1).then(2).then(Promise.resolve(3)).then(console.log) 执行结果
then 方法传入非函数会透传 |
const promise = Promise.resolve().then(() => { return promise }); 会报错 then/catch 不能返回 promise 本身,否则会造成死循环 |
Promise.resolve(1)
.then(res => { console.log(res) })
.finally(() => console.log('finally'));
Promise.resolve(2)
.finally(() => {
console.log('finally2');
return '我是 finally2 返回的数';
})
.then(res => {
console.log('finally2 后面的 then 函数', res);
}); 执行结果 1
finally2
finally
finally2 后面的 then 函数 2 特征
|
function runAsync(x) {
const p = new Promise(r => setTimeout(() => r(x, console.log(x)), 1000));
return p;
}
function runReject(x) {
const p = new Promise((res, rej) => setTimeout(() => rej(`Error:${x}`, console.log(x)), 1000 * x));
return p;
}
Promise.all([runAsync(1), runReject(4), runAsync(3), runReject(2)])
.then(res => console.log(res))
.catch(err => console.log(err)); 执行结果 // 1s
1
3
// 2s
2
Error: 2
// 4s
4 特征
|
async function async1() {
console.log('async start');
await async2();
console.log('async1 end');
setTimeout(() => {
console.log('timer1');
}, 0);
}
async function async2() {
setTimeout(() => {
console.log('timer2');
}, 0);
console.log('async2');
}
async1();
setTimeout(() => {
console.log('timer3');
}, 0);
console.log('start');
} 执行结果 async1 start
async2
start
async1 end
timer2
timer3
timer1 特征
|
const p1 = new Promise((resolve) => {
setTimeout(() => {
resolve('resolve3');
console.log('timer1');
}, 0);
resolve('resolve1');
resolve('resolve2');
}).then(res => {
console.log(res);
setTimeout(() => {
console.log(p1);
}, 1000);
}).finally(res => {
console.log('finally', res);
}) 执行结果 resolve1
finally undefiend
timer1
Promise{<resolved>: undefined} 特征 finally 的返回值如果在没有抛出错误的情况下默认会是上一个 Promise 的返回值,而这道题中的 finally 上一个 Promise 是 then,但是这个 then 并没有返回值,所以 跑 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
执行结果
The text was updated successfully, but these errors were encountered: