Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2. 实现Promise.finally #2

Open
Sunny-117 opened this issue Nov 3, 2022 · 3 comments
Open

2. 实现Promise.finally #2

Sunny-117 opened this issue Nov 3, 2022 · 3 comments

Comments

@Sunny-117
Copy link
Owner

/**
   * 无论成功还是失败都会执行回调
   * @param {Function} onSettled
   */
 Promise.prototype.finally = function (onSettled) {
    return this.then(
      (data) => {
        onSettled(); // 实现了收不到参数了
        return data;
      },
      (reason) => {
        onSettled();
        throw reason;
      }
    );
    // finally函数 返回结果应该是无效的
  }
  
/******test finally*******/
// 无论什么结果,都会运行
const pro = new Promise((resolve, reject) => {
  resolve(1);
});
const pro2 = pro.finally((d) => {
  console.log("finally", d); // 收不到d参数
  // 本身不改变状态,但是抛出一个错误,数据就会变成它的错误
  // throw 123;
  return 123; //不起作用
});
setTimeout(() => {
  console.log(pro2);
});
@weirong111
Copy link

Promise.prototype.myfinally = function (cb) {
  return this.then(
    async (data) => {
      await Promise.resolve(cb(data));
      return data;
    },
    async (err) => {
      await Promise.resolve(cb(err));
      throw err;
    }
  );
};

const pro = new Promise((resolve, reject) => {
  resolve(1);
});
const pro2 = pro.myfinally((d) => {
  console.log("finally", d); // 收不到d参数
  // 本身不改变状态,但是抛出一个错误,数据就会变成它的错误
  // throw 123;
  return 123; //不起作用
});

@YMnotafraid
Copy link

Promise.prototype.myfinally = function (callback) {
  return this.then(
    async (res) => {
      await callback();
      return res; //finally本质起传递的作用,这里的res是上一个then函数的返回值
    },
    async (err) => {
      await callback();
      throw err;
    }
  );
};

Promise.resolve(123)
  .then((res) => {
    console.log(res); //123
    return Promise.reject(456);
  })
  .myfinally(() => {
    console.log("finally");
    return "finally本身不返回值";
  })
  .then(
    () => {},
    (err) => {
      console.log(err); //123
      return 789;
    }
  )
  .myfinally(() => console.log("finally"))
  .then((res) => console.log(res)); //789

@cscty
Copy link

cscty commented Jun 18, 2023

Promise.prototype.Finally = function (fn) {
return new Promise((resolve, reject) => {
this.then((data) => {
fn();
resolve(data);
}).catch((err) => {
fn();
reject(err);
});
});
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants