Sabo Boz
Sabo Boz

Reputation: 2565

how to execute return statement without waiting for asynchronous function

In my typescript code I have the following:

await func(obj);
return { statusCode: 200}

However, doing this will cause a delay to happen with the return (since I presume it's waiting for func to finish running) - is there a way to return immediately while having func run entirely in the background?

Upvotes: 0

Views: 857

Answers (2)

xinthose
xinthose

Reputation: 3820

Just do not await the function call. Example below:

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function test() {
  await timeout(3000);
  console.log("done waiting");
}

async function test1() {
  timeout(3000);
  console.log("done immediately");
}

test();
test1();

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370589

Just don't await it?

// run func without waiting for it to finish
func(obj);

// return immediately
return { statusCode: 200}

Upvotes: 1

Related Questions