javascript - 流畅的异步 api 与 ES6 代理 javascript

标签 javascript es6-promise fluent es6-proxy chainable

所以……我有一些方法。每个方法都返回一个 promise 。

     myAsyncMethods: {
          myNavigate () {
            // Imagine this is returning a webdriverio promise
            return new Promise(function(resolve){ 
              setTimeout(resolve, 1000);
            })
          },
          myClick () {
            // Imagine this is returning a webdriverio promise
            return new Promise(function(resolve){
              setTimeout(resolve, 2000);
            })
          }
        }

我正在尝试进行端到端 测试,因此prom 链必须是线性的(第一次点击、下一步导航等)

现在,我可以做到这一点......

makeItFluent(myAsyncMethods)
    .myNavigate()
    .myClick()
    .then(() => myAsyncMethods.otherMethod())
    .then(() => /*do other stuff*/ )

...具有 ES6 代理功能:

function makeItFluent (actions) {
    let prom = Promise.resolve();
    const builder = new Proxy(actions, {
        get (target, propKey) {
            const origMethod = target[propKey];

            return function continueBuilding (...args) {
                // keep chaining promises
                prom = prom.then(() => (typeof origMethod === 'function') && origMethod(...args));

                // return an augmented promise with proxied object
                return Object.assign(prom, builder);
            };
        }
    });

    return builder;
};

但是,我不能做以下事情:

makeItFluent(myAsyncMethods)
    .myNavigate()
    .myClick()
    .then(() => myAsyncMethods.otherMethod())
    .then(() => /*do other stuff*/ )
    .myNavigate()

因为 then 不是代理方法,因此它不会返回 myAsyncMethods。我尝试代理 then 但没有结果。

有什么想法吗?

感谢开发者 ;)

最佳答案

我将从 yourAsyncMethods 返回包装的 Promises,它允许将同步和异步方法与 Proxy 和 Reflect 混合使用并以正确的顺序执行它们:

/* WRAP PROMISE */
let handlers;
const wrap = function (target) {
    if (typeof target === 'object' && target && typeof target.then === 'function') {
        // The target needs to be stored internally as a function, so that it can use
        // the `apply` and `construct` handlers.
        var targetFunc = function () { return target; };
        targetFunc._promise_chain_cache = Object.create(null);
        return new Proxy(targetFunc, handlers);
    }
    return target;
};
// original was written in TS > 2.5, you might need a polyfill :
if (typeof Reflect === 'undefined') {
    require('harmony-reflect');
}
handlers = {
    get: function (target, property) {
        if (property === 'inspect') {
            return function () { return '[chainable Promise]'; };
        }
        if (property === '_raw') {
            return target();
        }
        if (typeof property === 'symbol') {
            return target()[property];
        }
        // If the Promise itself has the property ('then', 'catch', etc.), return the
        // property itself, bound to the target.
        // However, wrap the result of calling this function.
        // This allows wrappedPromise.then(something) to also be wrapped.
        if (property in target()) {
            const isFn = typeof target()[property] === 'function';
            if (property !== 'constructor' && !property.startsWith('_') && isFn) {
                return function () {
                    return wrap(target()[property].apply(target(), arguments));
                };
            }
            return target()[property];
        }
        // If the property has a value in the cache, use that value.
        if (Object.prototype.hasOwnProperty.call(target._promise_chain_cache, property)) {
            return target._promise_chain_cache[property];
        }
        // If the Promise library allows synchronous inspection (bluebird, etc.),
        // ensure that properties of resolved
        // Promises are also resolved immediately.
        const isValueFn = typeof target().value === 'function';
        if (target().isFulfilled && target().isFulfilled() && isValueFn) {
            return wrap(target().constructor.resolve(target().value()[property]));
        }
        // Otherwise, return a promise for that property.
        // Store it in the cache so that subsequent references to that property
        // will return the same promise.
        target._promise_chain_cache[property] = wrap(target().then(function (result) {
            if (result && (typeof result === 'object' || typeof result === 'function')) {
                return wrap(result[property]);
            }
            const _p = `"${property}" of "${result}".`;
            throw new TypeError(`Promise chain rejection: Cannot read property ${_p}`);
        }));
        return target._promise_chain_cache[property];
    },
    apply: function (target, thisArg, args) {
        // If the wrapped Promise is called, return a Promise that calls the result
        return wrap(target().constructor.all([target(), thisArg]).then(function (results) {
            if (typeof results[0] === 'function') {
                return wrap(Reflect.apply(results[0], results[1], args));
            }
            throw new TypeError(`Promise chain rejection: Attempted to call ${results[0]}` +
                ' which is not a function.');
        }));
    },
    construct: function (target, args) {
        return wrap(target().then(function (result) {
            return wrap(Reflect.construct(result, args));
        }));
    }
};
// Make sure all other references to the proxied object refer to the promise itself,
// not the function wrapping it
Object.getOwnPropertyNames(Reflect).forEach(function (handler) {
    handlers[handler] = handlers[handler] || function (target, arg1, arg2, arg3) {
        return Reflect[handler](target(), arg1, arg2, arg3);
    };
});

您可以将它与您的方法一起使用

myAsyncMethods: {
      myNavigate () {
        // Imagine this is returning a webdriverio promise
        var myPromise = new Promise(function(resolve){ 
          setTimeout(resolve, 1000);
        });
        return wrap(myPromise)
      },
// ...

注意两件事:

你现在可以混合它了

FOO.myNavigate().mySyncPropertyOrGetter.myClick().mySyncMethod().myNavigate() ...

关于javascript - 流畅的异步 api 与 ES6 代理 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44116831/

相关文章:

javascript - Grails:模态 div 内的 g:uploadForm 抑制提交

javascript - 如何在嵌套数组中更新插入新字段

javascript - 等待循环与 Promise.all

swift - 了解 Vapor-Fluent 中的迁移(服务器端 Swift)

c# - 如何封装可观察到的长 react 链的创建

javascript - 在 nuxt 中使用 babel-polyfill (而不是 polyfill.io)

javascript - 如何让西蒙游戏正常运行

javascript - Firefox 43.0.2 中的“let”关键字不起作用

php - 返回 "self"作为 PHP trait 中函数的返回类型

javascript - 使用JQuery获取页面所有链接的 anchor 参数并替换目标链接的href