专业的编程技术博客社区

网站首页 > 博客文章 正文

前端面试——promise知多少(前端面试题promise)

baijin 2024-09-27 06:42:27 博客文章 5 ℃ 0 评论

异步编程的形式

+ 回调函数

+ 发布订阅模式

  let dep = {

    list: [],

    on: function(fn) {

      this.list.push(fn);

    },

    emit: function() {

      this.list.forEach(f => typeof f === 'function' ? f() : null)

    }

  }

+ promise

+ async和await

介绍下Promise,内部实现

Promise 也还是使用回调函数,只不过是把回调封装在了内部,使用上一直通过 then 方法的链式调用,使得多层的回调嵌套看起来变成了同一层的,书写上以及理解上会更直观和简洁一些。

> 状态: pending、fulfilled、rejected。

class Promise {

    callbacks = [];

    errorCbs = [];

    state = 'pending';

    value = null;

    constructor(fn) {

        fn(this.resolve.bind(this), this.reject.bind(this))

    }

    resolve(value) {

        this.state = 'fulfilled';

        this.value = value;

        this.callbacks.forEach((f) => f(value))

    }

    reject(value) {

        this.state = 'rejeted';

        this.value = value;

        this.callbacks.forEach((f) => f(value))

    }

    then(onFulfilled, onRejected) {

        if (this.state === 'pending') { //在resolve之前,跟之前逻辑一样,添加到callbacks中

            this.callbacks.push(onFulfilled);

            this.errorCbs.push(onRejected);

        } else if (this.state === 'fulfilled') { //在resolve之后,直接执行回调,返回结果了

            onFulfilled(this.value);

        } else {

            onRejected(this.value);

        }

        return this;

    }

}

promise、async有什么区别

如何设计Promise.all()

介绍Promise,异常捕获,Promise和Async处理失败的时候有什么区别

若是在promise的.then中出现错误的话,外层的trycatch代码块是捕获不到错误的,所以就需要再加一层.catch,才能捕获到.then里面的报错,但是这样会显得代码有点冗余。而假如写成注释的async/await的格式,一个try/catch可以同时对同步以及异步进行错误处理,代码更加简洁。

介绍下Promise的用途和性质Promise和Callback有什么区别

Async/Await怎么实现

Promise和setTimeout执行先后的区别(Event Loop)

JS为什么要区分微任务和宏任务

Promise构造函数是同步还是异步执行,then呢

a,b两个按钮,点击aba,返回顺序可能是baa,如何保证是aba(Promise.then)

Async里面有多个await请求,可以怎么优化(请求是否有依赖)

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表