How to get the return value of the setTimeout inner function in js All In One

在 js 中如何获取 setTimeout 内部函数的返回值

✅ Promise wrap & Async / Await

solution

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2022-10-18
 * @modified
 *
 * @description
 * @description
 * @difficulty EMedium
 * @time_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://www.cnblogs.com/xgqfrms/p/13849482.html
 * @solutions
 *
 * @best_solutions
 *
 */

const log = console.log;

// function debounce(func) {
//   var id;
//   return function (args) {
//     console.log(`args 1 =`, args);
//     var context = this;
//     // var args = arguments;
//     clearTimeout(id);
//     id = setTimeout(() => {
//       // func.apply(context, args);
//       // func.apply(context, [...args]);
//       func.apply(context, ...args);
//       // Uncaught TypeError: Spread syntax requires ...iterable[Symbol.iterator] to be a function
//     });
//   };
// };

// function debounce(func, delay) {
//   let id;
//   // ✅ ...rest 保证在不使用 arguments 的情况下,也可以传入不定数量的参数
//   return function (...args) {
//     console.log(`\nrest args =`, args);
//     console.log(`rest ...args =`, ...args);
//     console.log(`rest [...args] =`, [...args]);
//     let args1 = arguments;
//     let args2 = Array.prototype.slice.call(arguments, 0);
//     console.log(`args1 =`, args1);
//     console.log(`args2 =`, args2);
//     let context = this;
//     // let that = this;
//     clearTimeout(id);
//     id = setTimeout(() => {
//       // ✅ apply 接受参数数组 [arg1, arg2, ...]
//       func.apply(context, args);
//       // func.apply(context, [...args]);
//       // func.apply(context, ...args);
//       // Uncaught TypeError: CreateListFromArrayLike called on non-object
//       // ✅ call 接受参数列表 (arg1, arg2, ...)
//       func.call(context, ...args2);
//     }, delay);
//   };
// };

const debounce = (func, delay) => {
  let id;
  // ✅ ...rest 保证在不使用 arguments 的情况下,也可以传入不定数量的参数
  return async (...args) => {
    console.log(`\nrest args =`, args);
    console.log(`rest ...args =`, ...args);
    console.log(`rest [...args] =`, [...args]);
    let context = this;
    // let that = this;
    clearTimeout(id);
    // id = setTimeout(() => {
    //   // ✅ apply 接受参数数组 [arg1, arg2, ...]
    //   func.apply(context, args);
    //   // func.apply(context, [...args]);
    //   // ✅ call 接受参数列表 (arg1, arg2, ...)
    //   // func.call(context, ...args);
    // }, delay);
    const promise = new Promise((resolve, reject) => {
      id = setTimeout(() => {
        resolve(func.apply(context, args));
      }, delay);
    });
    // return promise;
    const result = await(promise);
    console.log(`result`, result);
    return result;
    // js how to get setTimeout inner function return value ✅ promise wrap  & async / await
  };
};

// function test (a, b, c, d) {
//   const args = [...arguments];
//   console.log(`test args =`, args);
// }

// const fn = debounce(test, 1000);

// fn(1,2,3);
// // fn(1,2,3,4);
// fn(1,2,3,4,5);

// 测试用例 test cases
const testCases = [
  {
    input: [1,2,3],
    result: '1,2,3',
    desc: 'value equal to "1,2,3"',
  },
  {
    input: [1,2,3,4],
    result: '1,2,3,4',
    desc: 'value equal to "1,2,3,4"',
  },
  {
    input: [1,2,3,4,5],
    result: '1,2,3,4,5',
    desc: 'value equal to "1,2,3,4,5"',
  },
];

function test (a, b, c, d) {
  const args = [...arguments];
  console.log(`test args =`, args);
  return args;
}

const func = debounce(test, 1000);

log(`func =`, func);
// func = [AsyncFunction (anonymous)]
// func = Promise { [Function (anonymous)] }


(async () => {
  for (const [i, testCase] of testCases.entries()) {
    async function testCaseAsyncFunc(i, testCase) {
      const result = await func(...testCase.input);
      log(`result =`, result);
      // result = Promise { <pending> }
      // TypeError: func is not a function
      log(`test case ${i} result: `, result.join() === testCase.result ? `✅ passed` : `❌ failed`, result);
      // log(`test case ${i} =`, testCase);
    }
    await testCaseAsyncFunc(i, testCase);
  }
})();


refs

如何使用 js 实现一个 debounce 函数 All In One

https://www.cnblogs.com/xgqfrms/p/13849482.html

如何使用 js 实现一个 throttle 函数 All In One

https://www.cnblogs.com/xgqfrms/p/13849487.html



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


原文地址:http://www.cnblogs.com/xgqfrms/p/16806941.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性