0

I want to call a function, that includes a sequelize query (returns an order) in an infinite loop, meaning to recall the function again when it is resolved, so searching always for a new order.

My original approach was

do {
    (async function () {
        var nextOrder = await getNextOrder()
        console.log("nextOrder",nextOrder)
    })(); 
} while (ENV == "development");

that is calling:

function getNextOrder() {
    return new Promise(async (resolve, reject) => {
        try {
            Orders.findOne({
                where: {
                    type: {
                        [Op.or]: ["buy", "sell"]
                    },
                },
            }).then(async nextOrder => {
                // Doing stuff with next order
                return resolve()
            }).catch(function (e) {
                console.log("error", e)
                return reject(e)
            })
        } catch (e) {
            console.log("error", e)
            return reject(e)
        }
    })
}

The problem with above approach is, that the function: getNextOrder never resolves and the while-loop just calls it permanently. What needs to be done to get above code working by calling the same function again and again, but after it resolved?

Now I ended up with the following approach, which is working, but it would be interesting to get the async/await approach above working.

getNextOrder()

that is calling:

function getNextOrder() {
    Orders.findOne({
        where: {
            type: {
                [Op.or]: ["buy", "sell"]
            },
        },
    }).then(async nextOrder => {
        // Doing stuff with next order
    }).then(function() {
        getNextOrder() // <------ Calling function again here
        return
    }).catch(function (e) {
        console.log("error", e)
        return
    })
}

1 Answer 1

1

You should not use async in the new Promise(async (resolve, reject) piece of the code OR use async/await inside the function:

function getNextOrder() {
    return new Promise(async (resolve, reject) => {
        try {
            const nextOrder = await Orders.findOne({
                where: {
                    type: {
                        [Op.or]: ["buy", "sell"]
                    },
                },
            })
            // Doing stuff with next order
            return resolve()
        } catch (e) {
            console.log("error", e)
            return reject(e)
        }
    })
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.