I just had to do a coding test that involved a Node GET call, parsing the return data and returning it to the calling function so that it could be printed to stdout. All went fine except I couldn't figure out how to get it out of the inner asynchronous function and then get the outer function to return it. The rules of the game, as I understand them, was that I could only work on the code within my interior function.
The first iteration I came up with was something like this (I'm leaving out the tricky processing of the data which the original test required)
const https = require('https')
function inner() {
let buff = ''
https.get('https://jsonplaceholder.typicode.com/posts', res => {
res.on('data', data => {
buff += data
})
res.on('end', () => {
return JSON.parse(buff)
})
})
}
function outer() {
const results = inner()
}
outer()
which doesn't work, because returning from the inner function res.on('end',...)
doesn't return from the outer.
Then I thought to bend the rules of the game a bit and use await
, which requires me to make my inner function async
. This works, up to a point. But now the async
function is returning a Promise, and I have no control over the outer function to unwrap it (it's part of the test environment).
const https = require('https')
async function inner() {
let buff = ''
const get = () => new Promise((resolve, reject) => {
https.get('https://jsonplaceholder.typicode.com/posts', res => {
res.on('data', data => {
buff += data
})
res.on('end', () => {
resolve(JSON.parse(buff))
})
})
})
try {
const results = await get()
return results
} catch (e) {
console.log(e.message)
}
}
function outer() {
const results = inner()
}
outer()
I'm sure there is a stupidly obvious answer, but I'm not seeing it. Perhaps there is a Promise-based method of on.('end')
that eliminates these inner functions? Any help finding the best solution much appreciated (and yes, the test is over, I'm just doing this for my own knowledge).