Skip to content

Support Promise-based operations in addition to callbacks #4

@ilyazub

Description

@ilyazub

Now only callbacks are supported for SerpApiSearch#json.

const { GoogleSearch } = require('google-search-results-nodejs')
const search = new GoogleSearch(process.env.API_KEY)

const params = {
  engine: 'google_maps',
  q: 'pizza',
  ll: '@40.7455096,-74.0083012,15.1z',
  type: 'search'
}

search.json(params, data => {
  console.log(data.local_results)
})

The workaround is to promisify functions, but out-of-the-box support would be great. Test with the workaround here.

const { GoogleSearch } = require('google-search-results-nodejs')
const search = new GoogleSearch(process.env.API_KEY)

function promisifiedGetJson(params) {
  return new Promise((resolve, reject) => {
    try {
      search.json(params, resolve)
    } catch (e) {
      reject(e)
    }
  })
}

const params = {
  engine: 'google_maps',
  q: 'pizza',
  ll: '@40.7455096,-74.0083012,15.1z',
  type: 'search'
}

async function main(params) {
  try {
    const data = await promisifiedGetJson(params)

    console.log('Local results\n')

    for (const localResult of data.local_results) {
      const { title, position, reviews } = localResult
      console.log(`Position: ${position}\nTitle: ${title}\nReviews: ${reviews}\n`)
    }
  } catch (error) {
    console.error('there was an error:', error)
  }
}

main(params)

PS. Node.js HTTPS module is used to send requests. got has a simpler API and the response stream is handled by the library.

search.get(url, (resp) => {
let data = ''
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk
})
// The whole response has been received. Print out the result.
resp.on('end', () => {
try {
if (resp.statusCode == 200) {
callback(data)
} else {
throw data
}
} catch (e) {
throw e
}
});
}).on("error", (err) => {
throw err;
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions