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

how to handle error in one promise and then to resolve and by-pass to next promise

如何在 js 中处理 promise,当您只需要将其绕过到下一个级别时。下面是我的代码。这里我写了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:\front\testPromises.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))