当前位置:首页 > JavaScript > 正文

JS异步和同步的方法运行的顺序

方法顺序执行,不论同步还是异步

以下代码实现方法顺序执行,不论同步还是异步,

js
 代码解读
复制代码
let result;
for (const f of [func1, func2, func3]) {
  result = await f(result);
}
/* use last result (i.e. result3) */

更老版本的写法:

js
 代码解读
复制代码
const applyAsync = (acc, val) => acc.then(val);
const composeAsync =
  (...funcs) =>
  (x) =>
    funcs.reduce(applyAsync, Promise.resolve(x));

const transformData = composeAsync(func1, func2, func3);
const result3 = transformData(data);

参考:MDN: 使用Promise

闭包缓存计算结果,提高性能

js
 代码解读
复制代码
function memoize(fn) {
    const cache = {};

    return function(...args) {
        const key = JSON.stringify(args);
        if (cache[key] !== undefined) {
            return cache[key];
        }
        const result = fn(...args);
        cache[key] = result;
        return result;
    };
}

function fibonacci(n) {
    if (n 在这个例子中,memoize 函数通过闭包缓存了计算结果,提高了递归函数的性能。闭包实现函数柯里化通用的函数柯里化工具函数,注意这里没有处理this的指向js
 代码解读
复制代码
function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      return fn(...args);
    }
    return function (...nextArgs) {
      return curried(...args, ...nextArgs);
    };
  };
}

function sum(a,b,c){
  return a+b+c;
}

const curriedSum = curry(sum);

console.log(curriedSum(1)(2)(3)); // 6
console.log(curriedSum(1, 2)(3)); // 6
console.log(curriedSum(1)(2, 3)); // 6TypeScript枚举+位运算进行状态判断枚举+位运算进行状态判断与运算typescript
 代码解读
复制代码
enum AnimalFlags {
  None        = 0,
  HasClaws    = 1 Animal 有多种状态时判断、运算十分简洁假如让我来写的话,不用枚举+位运算的话可能实现如下typescript
 代码解读
复制代码
type AnimalFlags = 'None' | 'HasClaws' | 'CanFly';
interface Animal {
  flags: AnimalFlags[];
  [key: string]: any;
}

function printAnimalAbilities(animal: Animal) {
  var animalFlags = animal.flags;
  if (!animalFlags || animalFlags.includes('None')) {
    return 'nothing';
  }
  if (animalFlags.includes('HasClaws')) {
    console.log('animal has claws');
  }
  if (animalFlags.includes('CanFly')) {
    console.log('animal can fly');
  }
}

var animal: Animal = { flags: ['None'] };
printAnimalAbilities(animal); // nothing
animal.flags = ['HasClaws'];
printAnimalAbilities(animal); // animal has claws
animal.flags = ['None'];
printAnimalAbilities(animal); // nothing
animal.flags = ['HasClaws', 'CanFly'];
printAnimalAbilities(animal); // animal has claws, animal can fly运算不太方便,比如状态是['HasClaws', 'CanFly'], 想移除Fly状态需要进行数组操作,比位运算麻烦许多

有话要说...