You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constrequest=require('request');doAsyncMath('2+15',function(result){doAsyncMath(`${result}*3`,function(result){doAsyncMath(`${result}*10`,console.log);});});/* * `doAsyncMath` constructs a URL with the help of the passed in * `expression`. Assuming the response callback is called, the * result will be passed into `doSomethingWithResult`. */functiondoAsyncMath(expression,doSomethingWithResult){constURL='https://newton.now.sh/simplify/';/* * The anonymous function definition passed in as the 2nd argument * to the `request` function will be called when and if a response * is received back from the API request made. */request(`${URL}${expression}`,function(err,response,body){letresult=getResultFrom(body);// Here the *defintion* passed in above is *called*.doSomethingWithResult(result);});}functiongetResultFrom(body){returnJSON.parse(body).result;}
Building a Promise from Scratch (verbose example)
// Before using the promise, we must create it.letpromise=newPromise(executor);functionexecutor(functionToResolvePromise,functionToRejectPromise){letvalueToResolvePromiseWith=7;functionToResolvePromise(valueToResolvePromiseWith);letvalueToRejectPromiseWith='epic failure';functionToRejectPromise(valueToRejectPromiseWith);}// Now that the promise has been created we can use itpromise.then(functionToBeGivenResolvedValue).catch(functionToBeGivenRejectedValue)functionfunctionToBeGivenResolvedValue(resolvedValue){console.log(`Here is the resolved value: ${resolvedValue}`);}functionfunctionToBeGivenRejectedValue(rejectedValue){console.log(`Here is the rejected value: ${rejectedValue}`);}
Using a Hand Made Promise to Refactor Callback Hell
functiondoAsyncMath(expression){constURL='https://newton.now.sh/simplify/';returnnewPromise(function(resolve,reject){request(`${URL}${expression}`,function(err,response,body){if(err){reject(err);}letresult=getResultFrom(body);resolve(result);});});}functiongetResultFrom(body){returnJSON.parse(body).result;}constrequest=require('request');letresult=doAsyncMath('2+15');result.then(function(resolvedValue){console.log(`InsidePromise1: ${resolvedValue}`);returndoAsyncMath(`${resolvedValue} * 10`);}).then(function(resolvedValue){console.log(`InsidePromise2: ${resolvedValue}`);returndoAsyncMath(`${resolvedValue} * 10`);}).then(function(resolvedValue){console.log(`InsidePromise3: ${resolvedValue}`);returndoAsyncMath(`${resolvedValue} * 10`);}).then(function(resolvedValue){console.log(`InsidePromise4: ${resolvedValue}`);returndoAsyncMath(`${resolvedValue} * 10`);}).catch(function(rejectedValue){console.log(`There was an error: ${rejectedValue}`);});
Refactoring to Use a Promise Producing Library (best)