1

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()
Anders Kitson
  • 1,413
  • 6
  • 38
  • 98
  • You need to call `checkPriceId`: `checkPriceId().then(...)` – blex Jan 24 '21 at 19:28
  • you don't want to call ```resolve``` on each document btw, you probably want to call ```resolve``` with an array of ```documents.sold``` (idem ```resolve(documents.map(x => x.sold))```) but first you may follow @blex instruction – grodzi Jan 24 '21 at 19:32

2 Answers2

3

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.

Zac Anger
  • 6,983
  • 2
  • 15
  • 42
2

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
})
James
  • 615
  • 1
  • 4
  • 22