promise & async/await

promise & async/await

promise

  1. 为什么出现promise?

    回调地狱

  2. promise的三个状态

    1. pending
    2. fullfilled
    3. rejected
  3. 真正解决回调地狱

    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);
      });
    
  4. promise的优雅

    promise链式执行,只需要在最后catch一个error

async/await

  1. async/await返回的是promise函数
  2. 对于一个async函数,在函数前面加上await代表的是停在这里等promise为resolve状态的时候再执行下面的代码,相当于下面的代码在promise的then里面
  3. 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

  1. 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';
};
posted @ 2022-06-18 02:44  kihyun  阅读(23)  评论(0编辑  收藏  举报