0

How do one change the following promise function into a async function.

const createRecord = (record) =>{
    return new Promise((resolve)=>{
        queue.push({
            id: Math.floor(Math.random()*100),
            callback: (id)=>{resolve(id);},
            data: record
        });
    });
};

I've tried the following code, but the function completes before the callback completes.

const createRecord = async (record) =>{
    queue.push({
        id: Math.floor(Math.random()*100),
        callback: (id)=>{return id;},
        data: record
    });
};

The callback is initiated by the following interval method;

var queue = [];

setInterval(() => {
    queue.forEach((record)=>{
        record.callback(record.id);
    });
}, 2000);
Peet
  • 1
  • What are you trying to achieve? Where do promises/async fit into anything? You seem to have synchronous code aside from the interval. But that interval doesn't seem dependent on `createRecord`. – VLAZ May 18 '21 at 13:05
  • Correct, createRecord and interval access the queue array variable totally independent. – Peet May 19 '21 at 13:33
  • So what's the problem? Why does `createRecord` need to happen asynchronously? – VLAZ May 19 '21 at 13:34

1 Answers1

2

The async and await keywords are tools to manage existing promises.

They can't be used to convert a callback based API into a promise based one. You still need to explicitly create and resolve a new Promise for that.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I agree with all you said but I don't even see why OP tries to use promises or async functions. Not of that code seems to be async. Aside from the interval but I'm not sure how the promises even work. Or what the goal is at all. – VLAZ May 18 '21 at 13:04