Promise 面试题

1. 看代码,说输出

new Promise((resolve, reject) => {
    for(let i = 0; i < 3; i++){
        resolve(i);
        console.log(i);
    }
}).then(data => console.log(data));

// 输出是:
// 0
// 1
// 2
// 0

2. async await 怎么处理错误

async await 从语法层面给人一种非常直观的方式,可以让我们避免 callback hell 与 Promise hell.

async function getUserInfo(){
    const id = await request.getCurrentUserId();
    const info = await request.getUserInfo(id);

    return info;
}

但是,每一步 await 都可能出错,为了捕获这些错误,我们使用 try...catch...

async function getUserInfo(){
    try{
        const id = await request.getCurrentUserId();
    } catch(e){
        return cb('an error in getCurrentUserId');
    }

    try{
        const info = await request.getUserInfo(id);
    }catch(e){
        return cb('an error in getUserInfo');
    }

    return cb(null, info);
}

这样的代码丑陋且不直观,因为 await 返回的是一个 Promise,因此可以使用一个函数包装一个来符合 error first 的原则,从而避免 try...catch...

function to(promise){
    return promise.then(data => {
        return [null, data];
    }).then(err => [err]);
}

通过这个函数包装一下上面的例子

async function getUserInfo(){
    let err, id, info;
    [err, id] = await to(request.getCurrentUserId());
    if(err){
        return console.error(err);
    }

    [err, info] = await to(request.getCurrentUserInfo());
    if(err){
        return console.error(err);
    }
    return info;
}

3. promise 什么时候错误不走 catch

全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务