错误处理方式
方式一 try...catchclassBookModel{fetchAll(){returnnewPromise((resolve, reject)=>{
window.setTimeout(()=>{reject({'error':400})},1000);});}}// async/awaitasyncgetBooksByAuthorWithAwait(authorId){try{const books =await bookModel.fetchAll();}catch(error){console.log(error);// { "error": 400 }}}
优点 方便,简单
可以集中处理,所有错误
缺点 不能准确定位错误的位置
classBookModel{fetchAll(){cb();// note `cb` is undefined and will result an exception returnfetch('/books');}}try{
bookModel.fetchAll();}catch(error){console.log(error);// This will print "cb is not defined"}
方式二 catch// books === undefined if error happens,// since nothing returned in the catch statementlet books =await bookModel.fetchAll().catch((error)=>{console.log(error);});
方式三 await-to-js
/**
* @param { Promise } promise
* @param { Object= } errorExt - Additional Information you can pass to the err object
* @return { Promise }
*/exportfunction to<T,U= Error>(
promise: Promise<T>,
errorExt?: object
): Promise<[U|null,T| undefined]>{return promise
.then<[null,T]>((data:T)=>[null, data]).catch<[U, undefined]>((err:U)=>{if(errorExt){
Object.assign(err, errorExt);}return[err, undefined];});}exportdefault to;import to from'../../dist';const UserModel ={
findById:(userId)=>{returnnewPromise((resolve, reject)=>{if(userId){const userObjet ={
id: userId,
notificationsEnabled:true};returnresolve(userObjet);}reject('Data is missing');});}};constTaskModel=function({userId, name}){returnnewPromise((resolve, reject)=>{if(userId && name){const newTask ={
assignedUser:{
id: userId
}};returnresolve(newTask);}reject('Data is missing');});};const NotificationService ={
sendNotification:(userId, name)=>{returnnewPromise((resolve, reject)=>{if(userId && name)returnresolve('Success');reject('Data is missing');});}};asyncfunctionasyncTask(userId, cb){let err, user, savedTask, notification;[ err, user ]=awaitto(UserModel.findById(userId));if(!(user && user.id))returncb('No user found');[ err, savedTask]=awaitto(TaskModel({userId: user.id, name:'Demo Task'}));if(err)returncb('Error occurred while saving task');if(user.notificationsEnabled){[ err ]=awaitto(NotificationService.sendNotification(user.id,'Task Created'));if(err)returncb('Error while sending notification');}if(savedTask.assignedUser.id !== user.id){[ err, notification ]=awaitto(NotificationService.sendNotification(savedTask.assignedUser.id,'Task was created for you'));if(err)returncb('Error while sending notification');}cb(null, savedTask);}asyncTask(1,(err, newTask)=>{console.log('new task created');console.log(err);console.log(newTask);});asyncTask(null,(err, newTask)=>{console.log('fail');console.log(err);console.log(newTask);});interfaceServerResponse{
test:number;}const p = Promise.resolve({test:123});const[err, data]=await to<ServerResponse>(p);console.log(data.test);
for(fname of files){let fcontent =awaitread(fname);
}
for(idx in files){let fcontent =awaitread(files[idx])}