对于`Promise`部分属性的理解

对于Promise.then()Promise.catch()的理解

今天碰到问题是这样子的:
调试bug的时候发现axios走了then也走了有catch,在我印象里是走了then就不应走catch(后来发现是我理解错了)
代码是这样的ios

this.axios.post('/user/login', params)
    .then(res => {
        console.log('response', res)
    })
    .catch(err => {
      // 这个catch catch的是then里的异常,then里若是有任何异常都会被catch捕获
        console.log('catch')
        console.error(err.message)
    })

仔细看了Promise.catch()MCDN是这样解释的axios

The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.prototype.then(undefined, onRejected) (in fact, calling obj.catch(onRejected) internally calls obj.then(undefined, onRejected)).

简单来说调用Promise.catch()等于调用Promise.prototype.then(undefined, onRejected)
因为Promise.then()返回的是一个Promise对象,返回值解释以下:segmentfault

throws an error, the promise returned by then gets rejected with the thrown error as its value;

若是抛出异常返回一个执行rejectedPromise对象即至关于调用返回PromisePromise.then(undefined, onRejected)promise

对于Promise.catch()的返回值是这样解释的:dom

The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.

若是Promise.catch()又抛出异常则至关于又调用Promise.then(undefined, onRejected)
若是未抛出异常则至关于调用Promise.then(onResolved,undefined)异步

promise.all()是顺序开始,异步执行,顺序返回

// 示例代码
const getRandom = () => +(Math.random()*1000).toFixed(0);

const asyncTask = taskID => new Promise(resolve => {
    let timeout = getRandom();
    console.log(`taskID=${taskID} start.`);
    setTimeout(function() {
        console.log(`taskID=${taskID} finished in time=${timeout}.`);
        resolve(taskID)
    }, timeout);
});

Promise.all([asyncTask(1),asyncTask(2),asyncTask(3)])
.then(resultList => {
    console.log('results:',resultList);
});

详见这里async

相关文章
相关标签/搜索