Created
August 6, 2015 15:39
-
-
Save roryashfordbentley/429e69e6b478a278d417 to your computer and use it in GitHub Desktop.
Stuck trying to get my noggin around callbacks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* getWpVersionInfo - gets the lates WordPress version and download links | |
* @param {Function} cb Callback function that is neccessary for data and errors | |
* @return {Object} Thisreturns selected data extracted from the api/json request | |
*/ | |
function getWpVersionInfo(cb) { | |
// Pass the API details to the http.get method | |
return http.get({ | |
host: 'api.wordpress.org', | |
path: '/core/version-check/1.7/' | |
}, function(response) { | |
// Ensure we get a usable encoded file | |
response.setEncoding('utf8'); | |
// Instantiate body as a blank var | |
var body = ''; | |
// Collect all the Async data into the body var | |
response.on('data', function (chunk){ | |
body += chunk; | |
}); | |
// On async completion parse the JSON or handle any parsing errors that arise | |
response.on('end', function(){ | |
try { | |
jsonData = JSON.parse(body); | |
} catch (err){ | |
console.error( chalk.red('Unable to parse WordPress Version from JSON.')); | |
return cb(err); | |
} | |
// Callback for handling errors and results | |
cb(null, { | |
wp_version: "Latest Version: " + jsonData.offers[0].current, | |
wp_full_download: jsonData.offers[0].packages.full, | |
wp_no_content_download: jsonData.offers[0].packages.no_content | |
}); | |
}); | |
// Handle any errors with the request | |
}).on('error', function(err) { | |
console.error(chalk.red('Error with request:', err.message)); | |
cb(err); | |
}); | |
} | |
// This totally works just fine | |
/*getWpVersionInfo(function(err,result){ | |
console.log(chalk.green(result.wp_version)); | |
console.log(chalk.green(result.wp_full_download)); | |
console.log(chalk.green(result.wp_no_content_download)); | |
});*/ | |
// This doesnt work and I can't get my head around how I should do it | |
// I need to get the string from 'result.wp_no_content_download' available as a var within installWordpress | |
function installWordpress(){ | |
getWpVersionInfo(function(err,result){ | |
var wp_download_location = result.wp_no_content_download; | |
}); | |
console.log(wp_download_location); //Nope | |
} | |
installWordpress(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment