I have a block of code that calls a JS function (NodeJS). The function it calls contains a Promise chain. Here is the code that calls the function:
'use strict'
const request = require('request')
try {
const data = search('javascript')
console.log('query complete')
console.log(data)
} catch(err) {
console.log(err)
} finally {
console.log('all done')
}
function search(query) {
searchByString(query).then( data => {
console.log('query complete')
//console.log(JSON.stringify(data, null, 2))
return data
}).catch( err => {
console.log('ERROR')
console.log(err)
throw new Error(err.message)
})
}
function searchByString(query) {
return new Promise( (resolve, reject) => {
const url = `https://www.googleapis.com/books/v1/volumes?maxResults=40&fields=items(id,volumeInfo(title))&q=${query}`
request.get(url, (err, res, body) => {
if (err) {
reject(Error('failed to make API call'))
}
const data = JSON.parse(body)
resolve(data)
})
})
}
When I run the code, the console displays query complete
followed by the search results.
Then I get an error: TypeError: google.searchByString(...).then(...).error is not a function
which doesn't make sense! Why does this error get triggered?