Skip to content Skip to sidebar Skip to footer

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

Solution 1:

  • Product.findOne and Document.findAll return a Promise, so they can be returned and awaited directly.
  • You can chain await func1(); await func2(); await func3() in one try{} block, and catch any error that happens in one place :
const filterFiles = async filePath => {
    const paths = awaitgetAllFiles(filePath);
    // .. Do something else herereturn paths // This is a Promise because async functions always return a Promise
}

constfindOneDoc = name => Product.findOne({ where: { name } }); // This func returns a PromiseconstfindAllDocs = product_id => Document.findAll({ // This func returns a Promise tooraw: true,
    where: { product_id }
});

(async () => {
    try {
        const childProduct = awaitfindOneDoc("some_name");
        console.log("All good until now!");
        const filePath = awaitfindAllDocs(childProduct._id);
        console.log("Still good");
        const filteredFiles = awaitfilterFiles(filePath);
        console.log("All went well.");
        console.log(filteredFiles);
    } catch (err) {
        // If any of the functions above fails, the try{} block will break and the error will be caught here. console.log(`Error!`, err);
    }
})();

Solution 2:

There are few things I would like to mention.

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

for ex-

functiontestPromise() {
  returnnewPromise((resolve, reject) => {
    // your logic// The followin if-else is not nessesary, its just for an illustrationif (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 awaitlet obj = awaittestPromise()

// OR call with then, but its better to go with awaittestPromise().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.

Post a Comment for "Resolve And Reject Issue Using Node Js"