返回介绍

solution / 2700-2799 / 2776.Convert Callback Based Function to Promise Based Function / README_EN

发布于 2024-06-17 01:03:00 字数 3748 浏览 0 评论 0 收藏 0

2776. Convert Callback Based Function to Promise Based Function

中文文档

Description

Write a function that accepts another function fn and converts the callback-based function into a promise-based function. 

The function fn takes a callback as its first argument, along with any additional arguments args passed as separate inputs.

The promisify function returns a new function that should return a promise. The promise should resolve with the argument passed as the first parameter of the callback when the callback is invoked without error, and reject with the error when the callback is called with an error as the second argument.

The following is an example of a function that could be passed into promisify.

function sum(callback, a, b) {
  if (a < 0 || b < 0) {
    const err = Error('a and b must be positive');
  callback(undefined, err);
  } else {
  callback(a + b);
  }
}

This is the equivalent code based on promises:

async function sum(a, b) {
  if (a < 0 || b < 0) {
  throw Error('a and b must be positive');
  } else {
  return a + b;
  }
}

 

Example 1:

Input: 
fn = (callback, a, b, c) => {
  callback(a * b * c);
}
args = [1, 2, 3]
Output: {"resolved": 6}
Explanation: 
const asyncFunc = promisify(fn);
asyncFunc(1, 2, 3).then(console.log); // 6

fn is called with a callback as the first argument and args as the rest. The promise based version of fn resolves a value of 6 when called with (1, 2, 3).

Example 2:

Input: 
fn = (callback, a, b, c) => {
  callback(a * b * c, "Promise Rejected");
}
args = [4, 5, 6]
Output: {"rejected": "Promise Rejected"}
Explanation: 
const asyncFunc = promisify(fn);
asyncFunc(4, 5, 6).catch(console.log); // "Promise Rejected"

fn is called with a callback as the first argument and args as the rest. As the second argument, the callback accepts an error message, so when fn is called, the promise is rejected with a error message provided in the callback. Note that it did not matter what was passed as the first argument into the callback.

 

Constraints:

  • 1 <= args.length <= 100
  • 0 <= args[i] <= 104

Solutions

Solution 1

type CallbackFn = (next: (data: number, error: string) => void, ...args: number[]) => void;
type Promisified = (...args: number[]) => Promise<number>;

function promisify(fn: CallbackFn): Promisified {
  return async function (...args) {
    return new Promise((resolve, reject) => {
      fn((data, error) => {
        if (error) {
          reject(error);
        } else {
          resolve(data);
        }
      }, ...args);
    });
  };
}

/**
 * const asyncFunc = promisify(callback => callback(42));
 * asyncFunc().then(console.log); // 42
 */

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文