Created
October 28, 2017 06:21
-
-
Save jarvisniu/e950bffb338738199fa998d39cf42966 to your computer and use it in GitHub Desktop.
4 methods of javascript async programming
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
| diamond! |
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
| var fs = require('fs') | |
| var co = require('co') // npm install co | |
| findTreasureCallback('map.txt') | |
| findTreasurePromise('map.txt') | |
| findTreasureGenerator('map.txt') | |
| findTreasureAsyncFunction('map.txt') | |
| function PromiseReadFile(url) { | |
| return new Promise(function (resolve, reject) { | |
| fs.readFile(url.trim(), 'utf-8', function (err, result) { | |
| if (err) { | |
| reject(err) | |
| } else { | |
| resolve(result) | |
| } | |
| }) | |
| }); | |
| } | |
| function findTreasureCallback (filename) { | |
| fs.readFile(filename, 'utf-8', function (err, result) { | |
| fs.readFile(result.trim(), 'utf-8', function (err, result) { | |
| console.log('You found: ' + result.trim()) | |
| }) | |
| }) | |
| } | |
| function findTreasurePromise(filename) { | |
| PromiseReadFile(filename) | |
| .then(PromiseReadFile) | |
| .then(function (treasure) { | |
| console.log('You found: ' + treasure) | |
| }) | |
| } | |
| function findTreasureGenerator(filename) { | |
| co(function *() { | |
| var treasureMap = yield PromiseReadFile(filename) | |
| var treasure = yield PromiseReadFile(treasureMap) | |
| console.log('You found: ' + treasure) | |
| }) | |
| } | |
| async function findTreasureAsyncFunction(filename) { | |
| var treasureMap = await PromiseReadFile(filename) | |
| var treasure = await PromiseReadFile(treasureMap) | |
| console.log('You found: ' + treasure) | |
| } |
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
| 0876.txt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment