JPG
JPG

Reputation: 1253

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

How to handle promises in js when you simply have to by-pass that to next level. Below is my code. Here I have written 3 functions download, compress and upload. Now suppose if there happens to be a case where no matching compressor found, in compress method, then I simply just want to continue to upload the raw fileName. Code below:

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))

As you can see there is no 77z compressor found in compress function. I just simply wanted to assign fileName to archive variable. But instead I got below error :

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

I know it didn't able to find fileName variable. But how can I solve this dilemma.

Upvotes: 0

Views: 58

Answers (1)

Wazeed
Wazeed

Reputation: 1280

Try this way:

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))

Upvotes: 1

Related Questions