Search code examples
javascriptpromisees6-promise

How to wait for a function in a promise?


I am trying to learn promises. I think I understand how it works if you use if and else with resolve and reject, but what if I have a function that returns a value? How can I make a promise that runs the function and when it is done it takes the returned value as its resolve promise? Here is an example of what I am trying to do (the result is nothing):

function test() {
    return 'Hi'
}

function getData() {
    const inOrder = new Promise((resolve, reject)=>{
        test()
    }).then((data)=> console.log('This is our data: ' + data))
}

Solution

  • Look into the documentation, you need to resolve your promise

    function test() {
        return 'Hi'
    }
    
    (function getData() {
        const inOrder = new Promise((resolve, reject)=>{
            resolve(test())
        }).then((data)=> console.log('This is our data: ' + data));
    })();