【JavaScript 】JavaScript 全教程 02
.then() 方法
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Result');
}, 200);
});
promise.then((res) => {
console.log(res);
}, (err) => {
console.error(err);
});
.catch() 方法
const promise = new Promise(
(resolve, reject) => {
setTimeout(() => {
reject(Error('Promise 无条件拒绝。'));
}, 1000);
});
promise.then((res) => {
console.log(value);
});
promise.catch((err) => {
console.error(err);
});
Promise.all()
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3);
}, 300);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 200);
});
Promise.all([promise1, promise2]).then((res) => {
console.log(res[0]);
console.log(res[1]);
});
链接多个 .then()
const promise = new Promise(
resolve =>
setTimeout(() => resolve('dAlan'),100)
);
promise.then(res => {
return res === 'Alan'
? Promise.resolve('Hey Alan!')
: Promise.reject('Who are you?')
})
.then((res) => {
console.log(res)
}, (err) => {
console.error(err)
});
避免嵌套的 Promise 和 .then()
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('*');
}, 1000);
});
const twoStars = (star) => {
return (star + star);
};
const oneDot = (star) => {
return (star + '.');
};
const print = (val) => {
console.log(val);
};
// 将它们链接在一起
promise.then(twoStars).then(oneDot).then(print);
JavaScript Async-Await
异步
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
// 异步函数表达式
const msg = async function() {
const msg = await helloWorld();
console.log('Message:', msg);
}
// 异步箭头函数
const msg1 = async () => {
const msg = await helloWorld();
console.log('Message:', msg);
}
msg(); // Message: Hello World! <-- 2 秒后
msg1(); // Message: Hello World! <-- 2 秒后
解决 Promises
let pro1 = Promise.resolve(5);
let pro2 = 44;
let pro3 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'foo');
});
Promise.all([pro1, pro2, pro3]).then(function(values) {
console.log(values);
});
// expected => Array [5, 44, "foo"]
异步等待 Promises
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
async function msg() {
const msg = await helloWorld();
console.log('Message:', msg);
}
msg(); // Message: Hello World! <-- 2 秒后
错误处理
// 数据不完整
let json = '{ "age": 30 }';
try {
let user = JSON.parse(json); // <-- 没有错误
console.log( user.name ); // no name!
} catch (e) {
console.error( "Invalid JSON data!" );
}
异步等待运算符
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
async function msg() {
const msg = await helloWorld();
console.log('Message:', msg);
}
msg(); // Message: Hello World! <-- 2 秒后
