Home > Net >  How do I call an async await function with delay interval ("Timeout"?) every 4 seconds?
How do I call an async await function with delay interval ("Timeout"?) every 4 seconds?

Time:11-29

I need to call a function every 4 seconds once, I figured I must use timeout, but I am not sure how to implement it with the async await

Here is my function code:

exports.sendWhatsappMessage = async (data) => {
    // Get > WhatsApp Client
    let client = wwjsInstances.getInstance(data.client_id)

    // Send > WhatsApp Message
    await client.sendMessage((data.recipient  '@c.us'), data.message).then(() => {
        console.log('DONE');
    });

    // Result Object
    let result = {
        ok: true,
        params: data,
        message: `[WhatsApp] : Task ${data.client_id}: Succeeded`
    }

    // Success
    return result;
};

I tried adding timeout to the promise but I am getting the error TypeError: resolve is not a function:

exports.sendWhatsappMessage = async (data) => {
    let client = wwjsInstances.getInstance(data.client_id)

    function timeout(ms) {
        client.sendMessage((data.recipient  '@c.us'), data.message).then(() => {
            console.log('DONE');
        });

        let myPromise = new Promise(function(resolve) {
            resolve(client)
        });

        // let something = await myPromise;
        return await myPromise;
    }

    async function sleep(fn, ...args) {
        await timeout(3000);
        return fn(...args);
    }

    let randomInterval = parseInt(((Math.random() * (0.5 - 1.0)   1.0) * 10000))

    await timeout(randomInterval);

    let result = {
        ok: true,
        params: data,
        message: `[WhatsApp] : Task ${data.client_id}: Succeeded`
    }

    // Success
    return result;
};

CodePudding user response:

function timeoutPromise(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
  
  
  const yourLogic = async() => {
  // your logic
  await CommonUtility.timeoutPromise(1001)
  // continue the logic after the timeout
  }
  • Related