Keep object chainable using async methods

前端 未结 3 1311
不思量自难忘°
不思量自难忘° 2021-01-13 06:22

Let\'s say I have a class Test with around 10-20 methods, all of which are chainable.

In another method, I have some asynchronous work to do.

         


        
3条回答
  •  旧时难觅i
    2021-01-13 07:22

    I don't think that is it possible to use such syntax for now. It would require to access the promise in the in the function to return it.

    Different ways to chain functions:

    Promise with then

    bob.bar()
        .then(() => bob.baz())
        .then(() => bob.anotherBaz())
        .then(() => bob.somethingElse());
    

    And you could also use compositions, to obtain another style of functional, reusable syntax to chain async and sync functions

    const applyAsync = (acc,val) => acc.then(val);
    const composeAsync = (...funcs) => x => funcs.reduce(applyAsync, Promise.resolve(x));
    const transformData = composeAsync(func1, asyncFunc1, asyncFunc2, func2);
    transformData(data);
    

    Or using async / await

    for (const f of [func1, func2]) {
      await f();
    }
    

提交回复
热议问题