zoukankan      html  css  js  c++  java
  • Promise的用法

    1.Promise.all 的用法;

    同时开始执行,而且每个promise的结果(resolve或reject时传递的参数值),和传递给 Promise.all 的promise数组的顺序是一致的。

    var promise = Promise.resolve(3);

    var promise2 = 42;

    var promise3 = 'foo';

     

    Promise.all([promise,promise2,promise3]).then(function(data){

     console.log(data);

    });

     

    打印结果:[ 3, 42, 'foo' ]

    function timerPromisefy(delay) {
    return new Promise(function (resolve) {
    setTimeout(function () {
    resolve(delay);
    }, delay);
    });
    }
    var startDate = Date.now();
    // 所有promise变为resolve后程序退出
    Promise.all([
    timerPromisefy(1),
    timerPromisefy(32),
    timerPromisefy(64),
    timerPromisefy(128)
    ]).then(function (values) {
    console.log(Date.now() - startDate + 'ms');
    // 約128ms
    console.log(values); // [1,32,64,128]
    });

     

    2.简单的Promise数据传递:两种写法

    new Promise(function(resolve){

    resolve('222222');

     

    }).then(function(data){

     console.log('promise传过来的data: '+data)

     

    })

    Promise.resolve(42).then(function(value){
    console.log(value);
    });

    3.Promise捕获异常问题;


    new Promise(function(resolve,reject){
    user.save(function(err,data){
    if(err){
    reject(err); //必须使用reject传出err,否则catch捕获不到
    }

    resolve(data);
    })
    }).then( function(data){
    console.log(data)

    }).catch( function(err){

    console.error('异常:'+err);

    })

    4.return和reject相似

    function A(){

    console.log('任务A');

    }

    function B(){

    console.log('任务B')

    }

    function C(){

    console.log('任务C');

    }

     

    function D(){

    return '这是D的数据返回';

    }

    var promise = Promise.resolve();

    promise.then(A).then(B).then(C).then(D).then(function(data){

    console.log(data);

    })

     

     

     

    // 2: 对 `then` 进行 promise chain 方式进行调用

    var bPromise = new Promise(function (resolve) {

        resolve(100);

    });

    bPromise.then(function (value) {

        return value * 2;

    }).then(function (value) {

        return value * 2;

    }).then(function (value) {

        console.log("2: " + value); // => 100 * 2 * 2

    });

     

    function anAsyncCall() {

        var promise = Promise.resolve();

        return promise.then(function() {

        // 任意处理

        return newVar;

    }); }

     

    更加详细Promise讲解,请参考:http://liubin.org/promises-book/#how-to-write-promise

  • 相关阅读:
    简易花台制作攻略
    欢迎
    VxWorks操作系统MakeFile(三)
    原创连载:往事
    VxWorks操作系统MakeFile(五)
    致亲爱的板儿的一封信
    VxWorks操作系统MakeFile(二)
    华为NE5000E集群路由器荣获InfoVision奖
    台式机安装黑苹果Mac OS X Snow Leopard 10.6相关资源
    未能加载文件或程序集Office, Version=2.2.0.0, Culture=neutral, PublicKeyToken=null或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配。 (异常来自 HRESULT:0x80131040)
  • 原文地址:https://www.cnblogs.com/qiyc/p/8629598.html
Copyright © 2011-2022 走看看