登录
首页 >  文章 >  前端

Promises/A+ 和异步等待 - JavaScript 挑战

来源:dev.to

时间:2024-11-28 21:33:41 226浏览 收藏

最近发现不少小伙伴都对文章很感兴趣,所以今天继续给大家介绍文章相关的知识,本文《Promises/A+ 和异步等待 - JavaScript 挑战》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

Promises/A+ 和异步等待 - JavaScript 挑战

您可以在 github 仓库中找到这篇文章中的所有代码。


异步编程 promises/a+ & async 等待相关挑战


使用 promise.finally() 实现 promises/a+

class mypromise {
  constructor(executor) {
    this.state = 'pending';
    this.value = undefined;
    this.reason = undefined;
    this.onfulfilledcallbacks = [];
    this.onrejectedcallbacks = [];

    const resolve = (value) => {
      if (this.state === 'pending') {
        this.state = 'fulfilled';
        this.value = value;
        this.onfulfilledcallbacks.foreach((callbackfn) => callbackfn(this.value));
      }
    } 

    const reject = (reason) => {
      if (this.state === 'pending') {
        this.state = 'rejected';
        this.reason = reason;
        this.onrejectedcallbacks.foreach((callbackfn) => callbackfn(this.reason));
      }
    }

    try {
      executor(resolve, reject);
    } catch (err) {
      reject(err);
    }
  }

  handlepromiseresult(result, resolve, reject) {
    if (result instanceof mypromise) {
      result.then(resolve, reject);
    } else {
      resolve(result);
    }
  }

  then(onfulfilled, onrejected) {
    onfulfilled = typeof onfulfilled === 'function'
      ? onfulfilled
      : (value) => value;
    onrejected = typeof onrejected === 'function'
      ? onrejected
      : (reason) => { throw reason; };

    // return a promise
    return new mypromise((resolve, reject) => {
      const fulfilledhandler = () => {
        queuemicrotask(() => {
          try {
            const result = onfulfilled(this.value);
            this.handlepromiseresult(result, resolve, reject);
          } catch (err) {
            reject(err);
          }
        });
      };

      const rejectedhandler = () => {
        queuemicrotask(() => {
          try {
            const result = onrejected(this.reason);
            this.handlepromiseresult(result, resolve, reject);
          } catch (err) {
            reject(err);
          }
        });
      };

      if (this.state === 'fulfilled') {
        fulfilledhandler();
      } else if (this.state === 'rejected') {
        rejectedhandler();
      } else {
        this.onfulfilledcallbacks.push(fulfilledhandler);
        this.onrejectedcallbacks.push(rejectedhandler);
      }
    });
  }

  catch(onrejected) {
    return this.then(null, onrejected);
  }

  finally(onfinally) {
    if (typeof onfinally !== 'function') {
      return this.then();
    }

    return this.then(
      (value) => mypromise.resolve((onfinally()).then(() => value)),
      (reason) => mypromise.resolve(onfinally()).then(() => { throw reason })
    );
  }

  static resolve(value) {
    return new mypromise((resolve) => resolve(value));
  }

  static reject(reason) {
    return new mypromise((_, reject) => reject(reason));
  }
}

// usage example
const promise = mypromise.resolve(1);
promise.then((value) => {
  console.log(value);
})
.then(() => {
  throw new error('error');
})
.catch((err) => {
  console.log(`error catched: ${err}`);
});

使用生成器实现异步等待

function asyncGenerator(generatorFunc) {
  return function (...args) {
    const generator = generatorFunc(...args);

    return new Promise((resolve, reject) => {
      function handle(iteratorResult) {
        if (iteratorResult.done) {
          resolve(iteratorResult.value);
          return;
        }

        Promise.resolve(iteratorResult.value)
          .then(
            (value) => handle(generator.next(value)),
            (err) => handle(generator.throw(err)),
          );
      }

      try {
        handle(generator.next());
      } catch (err) {
        reject(err);
      }
    });
  }
}

// Usage example
function* fetchData() {
  const data1 = yield fetch('https://jsonplaceholder.typicode.com/posts/1').then(res => res.json());
  console.log(data1);

  const data2 = yield fetch('https://jsonplaceholder.typicode.com/posts/2').then(res => res.json());
  console.log(data2);
}

// Create an async version of the generator function
const asyncFetchData = asyncGenerator(fetchData);

// Call the async function
asyncFetchData()
  .then(() => console.log('All data fetched!'))
  .catch(err => console.error('Error:', err));

参考

  • 67。创建你自己的 promise - bfe.dev
  • 123。实现 promise.prototype.finally() - bfe.dev
  • 承诺 - mdn
  • 异步函数 - mdn
  • 承诺/a+

本篇关于《Promises/A+ 和异步等待 - JavaScript 挑战》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>