简体   繁体   English

如何从承诺中的异步/等待返回错误

[英]how to return error from async/await inside promises

i initially wrote the code with promises, but due to a for loop had to use async/await.我最初用 Promise 编写代码,但由于 for 循环不得不使用 async/await。

the code works now, but i don't know how to throw the error which can work equivalent to reject of promise.该代码现在可以工作,但是我不知道如何抛出可以等效于拒绝 promise 的错误。

let createGroup=(data)=>{
                return new Promise((resolve,reject)=>{
                    if(check.isEmpty(data.groupName)){
                        reject('GroupId not Valid');
                    }
                    else{
                        let newGroup= new ExpenseModel({
                            groupId:'G-'+shortid.generate(),
                            groupName:data.groupName,
                            contributors:data.contributorObjIds,
                            timeCreated:time.now().format(),
                            creator:data.ownerId
                        })
                        newGroup.save((err,group)=>{
                            if(err){
                                reject(`Group Not Created ${err}`);
                            }else{
                                data.groupdata=group;
                                console.log("group created",data);
                                resolve(data);
                            }
                        })
                    }
                })
            }

            let updateUserData= async (data)=>{
                try{
                    for(user of data.contributorIds){
                        const res=await UserModel.findOne({'userId':user});
                        res.groups.push(data.groupdata._id);
                        const resSave=await res.save();
                        let id='GroupCreated'+user;

                        eventEmitter.emit('getGroup',user);    
                    }

                    return 1;
                }
                catch(e){
                    return e;
                }
            }



            createGroup(data)
            .then(updateUserData)
            .then((resolve)=>{
                let apiResponse = response.generate(false, 'Group created', 200, resolve);
                console.log(apiResponse);
            })
            .catch((err)=>{
                let apiResponse = response.generate(true, 'Group not saved', 400, null);
                console.log('group creation failed',err);
                 res.send(apiResponse);
            })

here in updateUserData how to check for errors while fetching data from db.updateUserData中,如何在从 db 获取数据时检查错误。 so that it finally goes to the catch block of the promise.这样它最终会进入 promise 的 catch 块。 and apiResponse of error is called.并调用错误的apiResponse

i don't know how to throw the error which can work equivalent to reject of promise.我不知道如何抛出可以等同于拒绝 promise 的错误。

Well, you should throw it not return it:-) Exceptions in an async function will cause the returned promise to reject.好吧,你应该throw它而不是return它:-) async function中的异常将导致返回的 promise 拒绝。

async function updateUserData(data) {
    try {
        for (user of data.contributorIds) {
            const res = await UserModel.findOne({'userId':user});
            res.groups.push(data.groupdata._id);
            const resSave = await res.save();
            let id = 'GroupCreated'+user;
            eventEmitter.emit('getGroup', user);
        }
        return 1;
    } catch(e){
        throw e;
//      ^^^^^
    }
}

However, catching an error with try / catch only to rethrow it without doing anything else is pointless, you should just let the exception bubble.但是,使用try / catch错误只是为了重新抛出它而不做任何其他事情是没有意义的,你应该让异常冒泡。 Simplify to简化为

async function updateUserData(data) {
    for (user of data.contributorIds) {
        const res = await UserModel.findOne({'userId':user});
        res.groups.push(data.groupdata._id);
        const resSave = await res.save();
        let id = 'GroupCreated'+user;
        eventEmitter.emit('getGroup', user);
    }
    return 1;
}

In a regular try..catch we can analyze the error and maybe rethrow it if can't handle.在常规的try..catch中,我们可以分析错误,如果无法处理,可能会重新抛出它。 The same thing is possible for promises.同样的事情也适用于 Promise。

If we throw inside .catch , then the control goes to the next closest error handler.如果我们在.catch中抛出,那么控件将转到下一个最近的错误处理程序。 And if we handle the error and finish normally, then it continues to the closest successful.then handler.如果我们处理错误并正常完成,那么它会继续到最近的successful.then 处理程序。

In the example below the .catch successfully handles the error:在下面的示例中, .catch成功处理了错误:

new Promise((resolve, reject) => {

  throw new Error("Whoops!");

}).catch(function(error) {

  alert("The error is handled, continue normally");

}).then(() => alert("Next successful handler runs"));

But inside each catch, we can trowing a new error if it remains unhandled, we can make sure it doesn't block the code and also return it at last.但是在每个捕获中,如果它仍未处理,我们可以抛出一个新错误,我们可以确保它不会阻塞代码并最终返回它。

// the execution: catch -> catch -> then
new Promise((resolve, reject) => {

  throw new Error("Whoops!");

}).catch(function(error) { // (*)

  if (error instanceof MyCustomEror) {
    // handle it
  } else {
    alert("Can't handle such error");

    throw error; // throwing this or another error jumps to the next catch
  }

}).then(function() {
  /* doesn't run here */
}).catch(error => { // (**)

  alert(`The unknown error has occurred: ${error}`);
  // don't return anything => execution goes the normal way

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM