Search code examples
javascriptnode.jsdropbox

My Promise going into both then and catch


I have a set of nested promises shown below. The expected behaviour here is for 1 to be printed, then 2 to be printed and then for the callback to be called under dropbox_functions.moveFolder('test', data.ui). However what is happening is that 1 is printed then 2 is printed and the 2.1 is printed, so the 2 promise is going into the then and the catch. I cant work out why.

dropbox_functions.createBatchFolder(data.ui)
        .then(function(response) {
          console.log('1')
          console.log(response)
          dropbox_functions.checkScannerFolderExists('test')  
            .then(function(response) {
              console.log('2')
              console.log(response)
              dropbox_functions.moveFolder('test', data.ui)
                .then(function(response) {
                  console.log(response)
                  callback(null, data)
                })
                .catch(function(error) {
                  console.log(error);
                  callback('Data not copied from scanner', data)
                });
            })
            .catch(function(error) {
                console.log('2.1')
                console.log(response)
                dropbox_functions.createDataFolder(data.ui)
                  .then(function(response) {                      
                    console.log(response)
                    callback('No scanned folder', data)
                  })
                  .catch(function(error) {
                    console.log(error);
                    callback('Data Folder not created', data)
                  });  
            });
            // callback(null, data)
        })
        .catch(function(error) {
          console.log('1.2')
          console.log(error)
          callback('Folder not created', data)
        });

Solution

  • There must be an error thrown, after execution of line console.log('2'). If an error thrown within a promise execution, the next immediate catch block will catch the particular error.

                  console.log('2')
                  console.log(response) <-- Here 
                  dropbox_functions.moveFolder('test', data.ui) <--- Here 
                    .then(function(response) {
                      console.log(response)
                      callback(null, data)
                    })
                    .catch(function(error) { <-- or here
                      console.log(error);
                      callback('Data not copied from scanner', data)
                    });