GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — JavaScript/Asynchronous-JavaScript/Promises.js at master · lgope/JavaScript Expand file tree/ Copy pathPromises.jsMore file actions 65 lines (51 loc) · 1.82 KB / Copy pathPromises.jsFile metadata and controls65 lines (51 loc) · 1.82 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 // From Callback Hell to Promises (ES6) /* Promises, which is an ES six feature designed specifically to deal with asynchronous JavaScript. In simple terms a promise is an object that keeps track about whether a certain event has happened already or not, and if it did happen, then the promise determines what happens next. A promise kind of implements the concept of a future value that we're expecting.*/ const getIDs = new Promise((resolve, reject) => { setTimeout(() => { resolve([523, 883, 432, 974]); }, 1500); }); const getRecipe = recID => { return new Promise((resolve, reject) => { setTimeout(ID => { const recipe = { title: 'Fresh tomato Pasta', Publisher: 'Lakshman' }; resolve(`${ID}: ${recipe.title}`); }, 1500, recID); }); }; const getRelated = Publisher => { return new Promise((resolve, reject) => { setTimeout(pub => { const recipe = { title: 'American Pizza', Publisher: pub }; resolve(`${pub}: ${recipe.title}`); // 3 }, 1500, Publisher); }); }; // this then method allows us to add an event handler for the case that the promise is fulfilled. So which means that there is a result. getIDs .then(IDs => { // so this argument here will be the result of the successful promise. console.log(IDs); // [ 523, 883, 432, 974 ] return getRecipe(IDs[2]); }) .then(recipe => { console.log(recipe); // 432: Fresh tomato Pasta return getRelated('Lakshman Gope'); }) .then(recipe => { console.log(recipe); // Lakshman Gope: American Pizza }) // if the promise rejected then catch method will catch the error. .catch(error => { console.log('Error: ' + error); }); |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |