如何处理一个承诺中的错误,然后解决并绕过下一个承诺



如何在js中处理承诺,而您只需将其绕过到下一个级别。下面是我的代码。在这里,我编写了3个函数downloadcompressupload。现在假设,如果碰巧在compress方法中没有找到匹配的压缩器,那么我只想继续上传原始fileName。以下代码:

function download(fileUrl){
return new Promise((resolve,reject)=>{
if(!fileUrl.startsWith('http'))
return reject(new Error('download url only supports http'));
console.log(`downloading from ${fileUrl}`);
setTimeout(()=>{
let fileName = fileUrl.split('/').pop();
console.log(`downloaded ${fileName}`);
resolve(fileName);
},3000);
});
}
function compress(fileName,fileFormat){
return new Promise((resolve,reject)=>{
if(['7z','zip','rar'].indexOf(fileFormat)===-1)
return reject(new Error('unknown compression not allowed'));
console.log(`compressing ${fileName}`);
setTimeout(()=>{
let archive = fileName.split('.')[0]+"."+fileFormat;
console.log(`compressed to ${archive}`);
resolve(archive);
},500);
});
}
function upload(fileUrl,archive){
return new Promise((resolve,reject)=>{
if(!fileUrl.startsWith('ftp'))
return reject(new Error('upload url only supports ftp'));
console.log(`uploading ${archive} to ${fileUrl}`);
setTimeout(()=>{
console.log(`uploaded ${archive}`);
},4000);
});
}

download('http://www.filess.com/image.jpg')
.then((fileName)=>compress(fileName,'77z'))
.catch((err)=>archive=fileName)
.then((archive)=>upload('ftp://www.filess.com',archive))
.catch((err)=>console.error(err))

如您所见,在compress函数中找不到77z压缩器。我只是想把fileName分配给archive变量。但我得到了以下错误:

ReferenceError: fileName is not defined
at d:fronttestPromises.js:39:22
at processTicksAndRejections (internal/process/task_queues.js:93:5)

我知道它找不到fileName变量。但是我该如何解决这个难题呢。

试试这个方法:

download('http://www.filess.com/image.jpg')
.then((fileName) => compress(fileName, '77z').catch(err => { /* Process with err */ return fileName }))
//.catch((err) => archive = fileName)
.then((archive) => upload('ftp://www.filess.com', archive))
.catch((err) => console.error(err))

最新更新