zoukankan      html  css  js  c++  java
  • 【windows8开发】异步编程之Promise(Javascript)

    Javascript是一种单线程语言,一旦运行一些耗时的处理,其他一切处理都会被阻塞。所以在Javascript中,异步处理显得尤为重要。由于Javascript只会运行在一个线程中,它的异步模式本质是把一些耗时的处理推迟到未来的某个时间点来运行,也正因如此,在Javascript的代码中往往充满了很多的回调处理。
    Windows Runtime中提供了Promise接口,利用这个接口可以很方便的实现异步处理和回调。
    看一段代码:
    var test = asyncFunc().then(
        function (result) {
             console.log("async completed and get result");
        },
        function (error) {
             console.log("error");
        },
        function (progress) {
             console.log("get progress");
        }
    );

    这里先解释以下promise.then方法,定义如下:
    promise.then(onComplete, onError, onProgress)
    onComplete为asyncFunc成功后执行的回调函数,OnError为asyncFunc发生错误时的回调处理,onProgress为asyncFunc中每次进行进度报告时的回调处理。

    promise.then算是promise最常用的一个方法,此外还有一个方法是promise.done,它的定义跟then完全相同,如下所示:
    promise.done(onComplete, onError, onProgress)

    它们之间有何区别呢?目前发现两点:
    1.then支持延续任务调用方式(Continuation tasks),而done不支持
    比如then可以这样用,而done不可以:
    func().then().then().then() 
    2. then会捕获未处理的异常然后把错误状态作为返回值返回,而done则会把异常直接抛出

    在以下文章中有promise.then方法的具体使用实例,大家可以参考下。
  • 相关阅读:
    c# 运算符 ? ??
    c# linq <未完>
    javasript this
    python3 闭包(一)
    dom 中的换行符
    (转)关于 awk 的 pattern(模式)
    linux note(1)
    python sqlite3
    python 特殊方法
    Go Example--锁
  • 原文地址:https://www.cnblogs.com/secbook/p/2655111.html
Copyright © 2011-2022 走看看