【问题标题】:How to wrap callback-function to get promise in WinJS?如何包装回调函数以在 WinJS 中获得承诺?
【发布时间】:2014-03-08 09:10:27
【问题描述】:

我想知道如何实现这样的转换:

fn(args, function (errors, results) {})

fn(args).then(function (results){})

通过简单地调用类似的东西

makePromise(fn, args).then(function (results))

WinJS 中。

背景:我有一个使用异步回调的预定义接口,但我想将它们用作承诺。

这样可以吗?甚至可能被 WinJS 直接支持?

【问题讨论】:

    标签: javascript winjs promise asynccallback


    【解决方案1】:

    不,我在official docs 中找不到这样的方法。但是,应该这样做:

    function makePromise(fn, args) {
        return new WinJS.Promise(function init(completeDispatch, errorDispatch) {
            fn(args, function handler(errors, results) {
                if (errors)
                    errorDispatch(errors);
                else
                    completeDispatch(results);
             });
        });
    }
    

    【讨论】:

    • 这是一个很好的基本示例。但请注意,您将失去任何函数作用域,因此您需要使用 this 绑定任何函数。类似:makePromise(fn.bind(this), args).then( ... ); 此外,这仅在传入的函数接受单个参数时才有效。
    • 是的,这确实松散了 context 和进一步的论点,但我认为 OP 不需要这些。它也会不必要地使示例复杂化:-)
    • 当然,我只是提到它以防它绊倒任何人。此示例适用于上述直接情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多