Skip to content Skip to sidebar Skip to footer

How To Avoid Async Functions In Javascript?

function CanPurchase() { return new Promise(function(resolve, reject){ var name = document.getElementById('name').value; var civilNumber = document.getElementById('civilNum

Solution 1:

There is no way to make code that calls an asynchronous API behave synchronously. If you want to interact with cloud-based (and most other modern) APIs, you will have to learn to work with asynchronous calls.

In your case, the code for CanPurchase can be a bit simpler, as you don't need to declare your own promise as far as I can see. It should be something like this:

functionCanPurchase() {
  var name = document.getElementById('name').value;
  var civilNumber = document.getElementById('civilNumber').value;

  var canPurchase_query = db.collection("observer").doc("purchase_record")
    .collection("record_set")
    .where("name", "==", name)
    .where("civilNumber", "==", civilNumber);
  var result = "";

  return canPurchase_query
    .get()
    .then(function (querySnapshot) {
      querySnapshot.forEach(function (doc) {
        result += doc.data().time;
      });
      return !result
    })
    .catch(function (error) {
      returnfalse;
    });
});

So this no longer has a custom Promise, but instead returns the value from within then and catch and then the query. This is a common pattern when using promises, and is called bubbling up the results.

You can now call this function with:

canPurchase().then(function(result) {
  if(!result) {
    alert('이번주에 이미 구매하셨습니다.');
  }
}

If you're OK with using some more modern JavaScript feature, you can use async/await to make this code look a bit more familiar:

async function CanPurchase() {
  ...
}

let result = await canPurchase();
if(!result) {
  alert('이번주에 이미 구매하셨습니다.');
}

Just keep in mind that this is syntactic sugar around the existing flow with promises, and does not change the fact that these are asynchronous calls.

Post a Comment for "How To Avoid Async Functions In Javascript?"