promise & async/await
promise & async/await
promise
-
为什么出现promise?
回调地狱
-
promise的三个状态
- pending
- fullfilled
- rejected
-
真正解决回调地狱
promise里面不嵌套then
每一个都返回一个promise再then
const readFilePro = (file) => { return new Promise((resolve, reject) => { fs.readFile(file, (err, data) => { if (err) reject('I could not find that file'); resolve(data); }); }); }; readFilePro(`${__dirname}/dog.txt`) .then((data) => { console.log(`Breed: ${data}`); return ( superagent .get(`https://dog.ceo/api/breeds/image/random`) ); }) .then((res) => { console.log(res.body.message); return writeFilePro('dog-img.txt', res.body.message); }) .then(() => { console.log('Random dog image saved to file!'); }) .catch((err) => { console.log(err.message); });
-
promise的优雅
promise链式执行,只需要在最后catch一个error
async/await
- async/await返回的是promise函数
- 对于一个async函数,在函数前面加上await代表的是停在这里等promise为resolve状态的时候再执行下面的代码,相当于下面的代码在promise的then里面
- async/await捕获错误用的是try/catch
const getDogPic = async () => {
try {
const data = await readFilePro(`${__dirname}/dog.txt`);
console.log(`Breed: ${data}`);
const res = await superagent.get(
`https://dog.ceo/api/breed/${data}/images/random`
);
// .get(`https://dog.ceo/api/breeds/image/random`);
console.log(res.body.message);
await writeFilePro('dog-img.txt', res.body.message);
console.log('Random dog image saved to file!');
} catch (err) {
console.log(err.message);
throw err;
}
return '2: READY';
};
promise.all
- promise.all返回的是多个promise执行之后的resolve值,是一个数组
const getDogPic = async () => {
try {
const data = await readFilePro(`${__dirname}/dog.txt`);
console.log(`Breed: ${data}`);
const res1Pro = await superagent.get(
`https://dog.ceo/api/breed/${data}/images/random`
);
const res2Pro = await superagent.get(
`https://dog.ceo/api/breed/${data}/images/random`
);
const res3Pro = await superagent.get(
`https://dog.ceo/api/breed/${data}/images/random`
);
const all = await Promise.all([res1Pro, res2Pro, res3Pro]);
const imgs = all.map((el) => el.body.message);
console.log(imgs);
await writeFilePro('dog-img.txt', imgs.join('\n'));
console.log('Random dog image saved to file!');
} catch (err) {
console.log(err.message);
throw err;
}
return '2: READY';
};