CommonSenseCode
CommonSenseCode

Reputation: 25399

Golang do an async task without awaiting

Some pseudocode describing my problem:

  1. Fetch a product from database a FoodProduct
  2. check if isExpired() FoodProduct.DueDate.Before(time.Now())
  3. if isExpired() then start async task to update the status of the FoodProduct in database as expired: FoodProduct.updateStatus("expired")

    [if isExpired()=false just skip to step 4.]

  4. return FoodProduct to client via http without awaiting for answer from step 3

I know go has goroutines, mutex and many other goodies. If I don't care about the result of async operation what option should I use?

Upvotes: 1

Views: 3739

Answers (1)

Adam Smith
Adam Smith

Reputation: 54223

just start the async task with the go keyword. It'll spin off in its own goroutine and your main line of execution doesn't have to care about it anymore.

product := fetchProduct()
if product.isExpired() {
        go product.updateStatus("expired")
}
// return as normal

Note that since product.updateStatus is almost certainly changing the state of that product, it's difficult to predict when it's safe to use that product again (aka when it's been updated in the underlying database layer)

Upvotes: 7

Related Questions