Anders Kitson
Anders Kitson

Reputation: 1545

new promise inside a async function in order to grab the value outside of the async function

I am returning a new Promis inside a async function that is doing a request to a api, I can console log the request from the api just fine inside the function. But when I try and resolve the same line I consoled document.sold it does not work. I expected the checkPriceId variable to return a promise which I could then catch with .then, but that does not seem to work. I have also tried using promise.all around the documents.forEach loop to no avail.

Any help would be greatly appreciated.

Here's the code

const checkPriceId = async test => {
      return new Promise((resolve, reject) => {
        const query = `*[_type == "products" && price_id == "${body.price_id}"]`
        client.fetch(query, {}).then(documents => {
          documents.forEach(document => {
            //console.log(document.sold)
            resolve(document.sold)
          })
        })
      })
    }

    checkPriceId.then(test => {
      console.log(test) // does nothing
    })

    console.log(checkPriceId) // just returns a async function

    checkPriceId()

Upvotes: 1

Views: 41

Answers (2)

James
James

Reputation: 774

As @blex mentinoned, you are not calling checkPriceId on line 13.

However, as also mentioned by @grodzi, you cannot resolve your promise multiple times. Once the resolve fn is called once (on line 7), subsequent calls will be ignored.

Since mixing Promises and async the way you are can be verbose and opaqueI'd suggest you just use async/awiat here. This will greatly help your code readability.

Here's a fixed example:

const checkPriceId = async (test) => {
  
  const query = `*[_type == "products" && price_id == "${body.price_id}"]`;

  const documents = await client.fetch(query, {}); // this could throw

  return documents.map(document => document.sold);
}

checkPriceId().then(test => {
  console.log(test) // this will log the return value from line 7
})

Upvotes: 2

Zac Anger
Zac Anger

Reputation: 7747

Why use the Promise constructor at all? client.fetch already returns a promise, and you're also inside an async function which also returns a promise. Assuming all documents have a .sold that you're trying to get back in an array:

const checkPriceId = async () => {
  const query = `*[_type == "products" && price_id == "${body.price_id}"]`
  const documents = await client.fetch(query, {})
  return documents.map(({ sold }) => sold)
}

checkPriceId.then((soldList) => {
  console.log(soldList)
})

This also removes the test argument to checkPriceId since it wasn't being used.

Upvotes: 3

Related Questions