promise学习笔记

Promise
  • 三种状态:pending(进行中)、fulfilled(已成功)、rejected(已失败)
  • Promise.prototype.then()
    • 作用是为 Promise 实例添加状态改变时的回调函数。前面说过,then方法的第一个参数是resolved状态的回调函数,第二个参数(可选)是rejected状态的回调函数。
  • Promise.prototype.catch()
    • Promise.prototype.catch方法是.then(null, rejection)的别名,用于指定发生错误时的回调函数
  • Promise.prototype.finally()
    • finally方法用于指定不管 Promise 对象最后状态如何,都会执行的操作
  • Promise.all()
    • Promise.all方法用于将多个 Promise 实例,包装成一个新的 Promise 实例
  • Promise.race()
    • Promise.race方法同样是将多个 Promise 实例,包装成一个新的 Promise 实例
  • Promise.resolve()
    • 参数是一个 Promise 实例
    • 参数是一个thenable对象
    • 参数不是具有then方法的对象,或根本就不是对象
    • 不带有任何参数
  • Promise.reject()
    • Promise.reject(reason)方法也会返回一个新的 Promise 实例,该实例的状态为rejected

 

	// promise学习
// example 1
const promise = new Promise((resolve, reject) => {
    var tag = true
    if (tag) {
        resolve(tag)
    } else {
        reject(tag)
    }
})
promise.then((tag) => {
    console.log('tag', tag)
    console.log("success")
}, (tag) => {
    console.log('tag', tag)
    console.log("fail")
})

// example 2
function timeout(ms){
    return new Promise((resolve,reject)=>{
        setTimeout(resolve,ms,'done')
        resolve()
    });
}
timeout(100).then((ms)=>{
    console.log('tag', ms)
});

// example 3
let promise = new Promise((resolve,reject)=>{
    console.log('Promise')
    resolve()
})
promise.then(()=>{
    console.log('resolves')
})
console.log('Hi !')

// example 4
const getJSON = function (url) {
    const promise = new Promise((resolve, reject) => {
        const handler = function () {
            if (this.readyState !== 4) {
                return
            }
            if (this.status === 200) {
                resolve(this.response)
            } else {
                reject(new Error(this.statusText))
            }
        }
        const client = new XMLHttpRequest()
        client.open("GET", url)
        client.onreadystatechange = handler
        client.responseType = "json"
        client.setRequestHeader("Accept", "application/json")
        client.send()
    });
    return promise;
}

// getJSON("http://127.0.0.1:8088/classTools/static/json/tools.json").then((json) => {
//     console.log('Content', json)
// }, (error) => {
//     console.log('error', error)
// })
// getJSON("http://127.0.0.1:8088/classTools/static/json/tools.json").then((post) => {
//    return getJSON(post.commentURL)
// }, (error) => {
//     console.log('error', error)
// }).then(function funcA(comments){
//     console.log("resolves",comments)
// },function funcB(err){
//     console.log("rejected",err)
// })
getJSON("http://127.0.0.1:8088/classTools/static/json/tools.json").then((posts) => {
    console.log(posts)
}).catch(error => {
    console.log('发送了错误', error)
})

// example 5
const p1 = new Promise((resolve, reject) => {
    setTimeout(() => reject(new Error('fail'), 3000))
})
const p2 = new Promise((resolve, reject) => {
    setTimeout(() => resolve(p1), 1000)
})
p2.then(result >= console.log(result)).catch(error => console.log(error))

// example 6
const someAsync =function(){
    return new Promise((resolve,reject)=>{
        resolve(x+2)
    })
}
someAsync().then(()=>{
    return someOtherAsync()
}).catch((error)=>{
    console.log('oh no',error)
    y+2;
}).catch((error)=>{
    console.log('carry on',error)
}).finally(()=>{
    console.log('finally')
})

// example 7
const p1 = new Promise((resolve, reject) => {
    resolve('hello')
}).then(result => result)
    .catch(e => e)

const p2 = new Promise((resolve, reject) => {
    throw new Error('报错了')
}).then(result => result)
    .catch(e => e)
Promise.all([p1, p2]).then(result => console.log(result))
    .catch(e => console.log(e))

// example 8
const p = Promise.race([
    fetch('/classTools/static/json/tools.json'),
    new Promise((resolve,reject)=>{
        setTimeout(()=>reject(new Error('request timeout')),5000)
    })
])
p.then(console.log).catch(console.error)

// example 9
function getFoo() {
    return new Promise((resolve, reject) => {
        resolve('foo')
    })
}
const g = function* () {
    try {
        const foo = yield getFoo()
        console.log(foo)
    } catch (e) {
        console.log(e)
    }
}
function run(generator) {
    const it = generator()
    function go(result) {
        if (result.done)
            return result.value
        return result.value.then((value) => {
            return go(it.next(value))
        }, function (error) {
            return go(it.throw(error))
        })
    }
    go(it.next)
}
run(g)

// example 10
var fn = function(num) {
    return new Promise(function(resolve, reject) {
        if (typeof num == 'number') {
            resolve(num);
        } else {
            reject('TypeError');
        }
    })
}
fn(2).then(function(num) {
    console.log('first: ' + num);
    return num + 1;
})
.then(function(num) {
    console.log('second: ' + num);
    return num + 1;
})
.then(function(num) {
    console.log('third: ' + num);
    return num + 1;
});

原文链接请看我的个人网站:链接跳转

你可能感兴趣的:(web前端,promise,es6)