Skip to content
Advertisement

resolve and reject issue using node js

  • Is this possible way to return resolve or reject message from one function to another?

  • As I am writing to pass resolve message in postman whenever my task is completed or reject message when there is some error

  • But after after writing return it still not returning the resolve message or reject message inside Postman

any idea how this can be resolve?

async function readFile(filePath) {}

async function getAllFile(filePath) {
const paths = await readFile(filePath);
}
async function filterFiles(filePath) {
const paths = await getAllFile(filePath);
}

function addDocument(childProduct){
return new Promise((resolve, reject) => {
Document.create({
        name: childProduct,
      },
    }).then(function (filePath) {
        filterFiles(filePath);
        let msg = "Document created Succesfully";
        return resolve(msg);
      })
      .catch(function (err) {
        return reject("Can't be updated please try again :) " + err);
      });
});
}
function updateDoc(data){
return new Promise((resolve, reject) => {
Document.update({
      name: data.name,
      }
      where: {
        product_id: data,
      },
    })
}).then(function (childProduct) {
        addDocument(childProduct);
        let msg = "Updated Successfully";
        return resolve(msg);
      })
      .catch(function (err) {
        return reject("Can't be updated please try again :) " + err);
      });
}

Advertisement

Answer

There are few things I would like to mention.

When you create a promise, it should have resolve() and reject() inside it.

for ex-

function testPromise() {
  return new Promise((resolve, reject) => {
    // your logic
    // The followin if-else is not nessesary, its just for an illustration
    if (Success condition met) {
        resolve(object you want to return);
    }else {
        reject(error);
        // you can add error message in this error as well
    }

 });
}
// Calling the method with await
let obj = await testPromise()

// OR call with then, but its better to go with await
testPromise().then((obj)=>{
   // Access obj here
})

In the method which you have written, You have applied .then() method to non promise object. You have to complete the promise block first with resolve() and reject() inside it. Then you can return that promise from a function, use it in async function Or apply .then() block on it.

Also you don’t need to add return statement to resolve() and reject() statement. The system will take care of it.

You can also use try catch block inside a promise. Its better to write reject() statement in catch block, if anything goes wrong.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement