0
  • 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);
      });
}
Aakash
  • 139
  • 1
  • 3
  • 22
  • Several things are wrong here. First you have a syntax error `Promise()..then()` (double `..`). You are creating Promises that never resolve and never do anything, so `.then()` will never happen. Then what anyway? `.then(function (childProduct) {`? What is `childProduct` in this case, since the Promise is empty and never resolves? Get rid of Promises entirely, and just use `async` functions. An `async` function _always_ returns a Promise; if you write `return "test"`, the returned type is `Promise`, not ``. – Jeremy Thille Apr 21 '21 at 09:01
  • Hello @JeremyThille I have updated the question I hope now its understandable please have a look :) – Aakash Apr 21 '21 at 09:11
  • Indeed, a big chunk of code was missing, it's clearer now. I've posted an answer. However I don't understand your function naming. `addDocument` finds one document? `updateDoc` finds all documents? This naming doesn't make sense – Jeremy Thille Apr 21 '21 at 09:28
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Apr 21 '21 at 09:41
  • Hi @JeremyThille by mistakenly I wrote down findAll findOne Code in my function I have updated the code – Aakash Apr 21 '21 at 10:09

2 Answers2

2
  • 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 = await getAllFiles(filePath);
    // .. Do something else here
    return paths // This is a Promise because async functions always return a Promise
}

const findOneDoc = name => Product.findOne({ where: { name } }); // This func returns a Promise

const findAllDocs = product_id => Document.findAll({ // This func returns a Promise too
    raw: true,
    where: { product_id }
});

(async () => {
    try {
        const childProduct = await findOneDoc("some_name");
        console.log("All good until now!");
        const filePath = await findAllDocs(childProduct._id);
        console.log("Still good");
        const filteredFiles = await filterFiles(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);
    }
})();
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • Hi @jeremy how can i show reject resolve msg from function? as i have wrote only two promise function here but in my code there are 9 promise function and i want to show there reject resolve msg on my postman – Aakash Apr 21 '21 at 10:12
  • Well, in the `catch` block naturally. I told you, all errors will be caught in one place. No need to catch 9 errors at 9 different places. Isn't the last line of code `console.log('Error!', err)` ? – Jeremy Thille Apr 21 '21 at 10:19
  • and what about resolve msg? As in every function there is different msg thats why :) – Aakash Apr 21 '21 at 10:22
  • Hello @Jeremy in my above question i get object `product` when i write `findAll, findOne or create` from my document and by this object i can fetch ID which act as foreign key to other data that's why i need above method if I use your method then how will i get object – Aakash Apr 22 '21 at 09:26
  • I'm not sure I understand the question. How will you get objects? You mean Mongo objects? Well that's exactly what the query returns, full objects – Jeremy Thille Apr 22 '21 at 11:19
1

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.

pritampanhale
  • 106
  • 10