skip to Main Content

I’ll be as brief as possible. Here is simple example

function find5 (arr)
{
    return new Promise (function (resolve, reject)
    {
        arr.forEach (
            function (el)
            {
                console.log (el);
                if (el == 5)
                {
                    return resolve (true);
                }
            }
        );
        return reject (false);
    });
}
async function init ()
{
    try {
        var res = await find5 ([1,2,3,4,5,6,7,8,9,10]);
        console.log (res);
    } catch (e) {
        console.log (e);
    }
}
init ();

Here is output: 1 2 3 4 5 6 7 8 9 10 true
I want to exit from function find5 but return resolve (true);. I think it returns from function (el). How do I jump here: return new Promise?

Need help with code.

4

Answers


  1. Chosen as BEST ANSWER
    //https://stackoverflow.com/questions/77240304/return-from-function-with-promise
    
    function find5 (arr)
    {
        return new Promise (function (resolve, reject)
        {
            var finded = false;
            arr.forEach (
                function (el)
                {
                    if (finded == false)
                    {
                        console.log (el);
                        if (el == 5)
                        {
                            finded = true;
                        }
                    }
                }
            );
            if (finded == true)
            {
                return resolve (true);
            }
            return reject (false);
        });
    }
    async function init ()
    {
        try {
            var res = await find5 ([1,2,3,4,5,6,7,8,9,10]);
            console.log (res);
        } catch (e) {
            console.log (e);
        }
    }
    init ();
    

    It's bad code, I know, but as an option.


  2. You can simplify this a lot using async syntax instead of returning an explicit Promise, and by using one of the many super useful Array functions that JS has built in (you definitely want to give the list over on the Array docs a read-through, there are way more than you think):

    async function find5(arr) {
      if (!arr) {
        throw new Error(`no input array passed to find5!`);
      }
      if (!Array.isArray(arr)) {
        throw new Error(`input to find5 was not an array!`);
      }
      // this will either be true, or false.
      return arr.some((e) => (e === 5));
    }
    
    async function init(arr) {
      try {
        const res = await find5(arr);
        console.log(res);
      } catch (e) {
        console.error(e.message);
      }
    }
    
    init();
    init("lol");
    init([1,2,4,8,16]);
    init([1,2,3,4,5,6,7,8,9,10]);

    And note that the find5 function shouldn’t be throwing an error just because you can’t find the element (or in Promise terms, should not be rejecting): that’s an "emergency" mechanism for when unexpected things happen. For instance, if arr is undefined or it’s not an array, that’s grounds to throw an error, but the array not containing an element 5 is not. The code still works, and finishes, it just didn’t see the element so it reports false.

    Login or Signup to reply.
  3. You cannot return inside a forEach in javaScript .. So your loop just continues to run. You can read more about that Here Array.prototype.forEach() — You’ll find in the docs:

    Return value
    None (undefined).

    To properly do it, your going to need a for loop instead.

    function find5(arr) {
      return new Promise(function(resolve, reject) {
        for (let i = 0; i < arr.length; i++) {
          console.log(arr[i]);
          if (arr[i] === 5) {
            console.log('made');
            return resolve(true);
          }
        }
    
        return reject(false);
      });
    }
    async function init() {
      try {
        var res = await find5([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
        console.log(res);
      } catch (e) {
        console.log(e);
      }
    }
    init();
    Login or Signup to reply.
  4. In JavaScript, when you use the return statement inside a callback function like the one you have in the forEach loop, it doesn’t actually exit the outer function (find5 in this case). Instead, it only exits the current callback function (function (el)). This is why the return resolve(true) statement does not exit the find5 function.

    If you want to exit the find5 function when you find the value 5 and resolve the promise, you can use a for loop instead of forEach, and then you can break out of the loop when the condition is met. Here’s a modified version of your code:

    function find5(arr) {
        return new Promise(function (resolve, reject) {
            for (let i = 0; i < arr.length; i++) {
                const el = arr[i];
                console.log(el);
                if (el === 5) {
                    resolve(true);
                    return; // Exit the function after resolving
                }
            }
            reject(false); // Reject if 5 is not found
        });
    }
    
    async function init() {
        try {
            var res = await find5([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
            console.log(res);
        } catch (e) {
            console.log(e);
        }
    }
    
    init();
    

    With this code, when el is equal to 5, it will resolve the promise and then use return to exit the find5 function, ensuring that it doesn’t continue iterating over the array unnecessarily.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search