Angular2(四)--promise

来源:互联网 发布:神机配模软件 编辑:程序博客网 时间:2024/05/19 11:46

angular生命周期方法:
每个方法名称是在该接口名加前缀ng
使用angular生命周期需要实现相应的接口,才能使用其生命周期方法

Promise异步技术使用then()方法注册,异常处理使用catch()方法
创建一个Promise对象:

const p = new Promise(    function (resolve, reject) { // (A)        ···        if (···) {            resolve(value); // success        } else {            reject(reason); // failure        }    });

使用promise:

promise.then(value => { /* fulfillment */ }).catch(error => { /* rejection */ });

http promise实例:
1.创建

function httpGet(url) {    return new Promise(        function (resolve, reject) {            const request = new XMLHttpRequest();            request.onload = function () {                if (this.status === 200) {                    // Success                    resolve(this.response);                } else {                    // Something went wrong (404 etc.)                    reject(new Error(this.statusText));                }            };            request.onerror = function () {                reject(new Error(                    'XMLHttpRequest Error: '+this.statusText));            };            request.open('GET', url);            request.send();        });}

2.使用

httpGet('http://example.com/file.txt').then(    function (value) {        console.log('Contents: ' + value);    },    function (reason) {        console.error('Something went wrong', reason);    });

使用setTimeout()方法可延时

//For most values x, it returns a Promise that is fulfilled with xPromise.resolve('abc')  .then(x => console.log(x)); // abc//Promise.reject(err) returns a Promise that is rejected with errconst myError = new Error('Problem!');Promise.reject(myError).catch(err => console.log(err === myError)); // true

If you resolve the Promise Q returned by then() with a normal value, you can pick up that value via a subsequent then():

asyncFunc().then(function (value1) {    return 123;}).then(function (value2) {    console.log(value2); // 123});

较好的实践:
1.return完整的Promise

function foo() {    return asyncFunc()    .then(result => {        ···    });}

2.嵌套类型

asyncFunc1().then(result1 => {    return asyncFunc2();}).then(result2 => {    ···});

3.不要为了创建promise而创建,当promise参数并无用处时,可以通过then()为我们产生promise

0 0
原创粉丝点击