Search code examples
javascriptasync-awaites6-promise

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()

Solution

  • 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
    })