0

I am using vue.js 2.* . I want to perform an action on an item but first, I check if this item exists and if not, I go fetch it through an API. My current code looks like this :

if (myItem == null) {
    this.goFetchItem().then(response => {
    myItem.performAction()
  })
} else {
  myItem.performAction()
}

I'd like to know if it possible to have somthing in the idea of :

if (myItem == null) {
    this.goFetchItem()
}
//And then, when item is fetched :
myItem.performAction()

For now,,in the second example, it seems goFetchItem() is executed asynchronoulsy, so myItem is still null when trying to perform the action.

Tom
  • 1,357
  • 2
  • 13
  • 32
  • 1
    `in the second example, it seems goFetchItem() is executed asynchronoulsy, so myItem is still null` -- That's why your first example uses `.then`. – Robert Harvey Aug 27 '18 at 16:14
  • I know, the first example is my actual code. I am curious to know if there is a solution to write something looking like the second example, since I only write the line `performAction()` once. Shorter and cleaner. But I can't stick a `then` after the `if`. My code works, i'm juste trying to make it cleaner. – Tom Aug 27 '18 at 16:16
  • 1
    Probably you would prefer to wrap the logic `check myItem is null then fetch from backend` into one promise, then always call `perfromAction` inside `Promise.final` – Sphinx Aug 27 '18 at 16:18
  • the duplicate lists all the possible ways to handle this scenario. – Jonas Wilms Aug 27 '18 at 16:24

1 Answers1

1

How about using async / await?

async function foo() {
    if (myItem == null) {
        await this.goFetchItem()
    }

    myItem.performAction()
}

check this out.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Javascript Promises vs Async Await. Difference?

Jae Woo Woo
  • 901
  • 1
  • 8
  • 19
  • Perfect ! I did not know about the `await` keyword (pretty new to JS). Thank you ! – Tom Aug 27 '18 at 16:23