[关闭]
@JunQiu 2018-09-18T09:52:49.000000Z 字数 4317 阅读 514

node_async回值 fetch,axios,retry/rate-limit_func

summary_2018/06 language_node npm


1、日常工作


2、技术学习

  1. //some test:
  2. const fc=require('fetch')
  3. async function test () {
  4. const data=await Promise.resolve('1111')
  5. console.log('data:'+data)
  6. return 'aaa'
  7. }
  8. /*
  9. console.log(test())
  10. 直接调用async返回promise对象,async函数中的异步操作
  11. 返回值:
  12. Promise { <pending> } //函数直接返回promise对象
  13. data:1111 //await完成后
  14. */
  15. /*
  16. async function test2(){
  17. a=await test()
  18. console.log(a)
  19. }
  20. test2()
  21. 返回值:等待promis对象完成后返回
  22. data:1111
  23. aaa
  24. */
  1. ### Fetch from URL
  2. fetch.fetchUrl(url [, options], callback)
  3. - url is the url to fetch
  4. - options is an optional options object
  5. - callback is the callback to run - callback(error, meta, body)
  6. ### Streaming
  7. fetch.FetchStream(url [, options]) -> Stream
  8. - url is the url to fetch
  9. - options is an optional options object
  10. ### options
  11. - maxRedirects how many redirects allowed, defaults to 10
  12. - headers optional header fields, in the form of {'Header-Field':'value'}
  13. - maxResponseLength maximum allowd length for the file, the remainder is cut off. Defaults to Infinity
  14. - method defaults to GET
  15. - payload request body
  16. - cookies an array of cookie definitions in the form of ['name=val']
  17. - timeout set a timeout in ms
  18. ### example
  19. options = {
  20. headers:{
  21. "X-My-Header": "This is a custom header field"
  22. }
  23. }
  24. options = {
  25. cookies: ["name=value", "key=value; path=/; secure"]
  26. }
  27. # Piping to file(FetchStream is a readable Stream )
  28. out = fs.createWriteStream('file.html');
  29. new FetchStream("http://www.example.com/index.php").pipe(out);
  1. ### Example
  2. axios.get('/user?ID=12345')
  3. .then(function (response) {
  4. console.log(response);
  5. })
  6. .catch(function (error) {
  7. console.log(error);
  8. });
  9. axios.get('/user', {
  10. params: {
  11. ID: 12345
  12. }
  13. })
  14. .then(function (response) {
  15. console.log(response);
  16. })
  17. .catch(function (error) {
  18. console.log(error);
  19. });
  20. axios.post('/user', {
  21. firstName: 'Fred',
  22. lastName: 'Flintstone'
  23. })
  24. .then(function (response) {
  25. console.log(response);
  26. })
  27. .catch(function (error) {
  28. console.log(error);
  29. });
  30. ## we can use promise.all
  31. function getUserAccount() {
  32. return axios.get('/user/12345');
  33. }
  34. function getUserPermissions() {
  35. return axios.get('/user/12345/permissions');
  36. }
  37. axios.all([getUserAccount(), getUserPermissions()])
  38. .then(axios.spread(function (acct, perms) {
  39. // Both requests are now complete
  40. }));
  41. ### axios(config)
  42. // Send a POST request
  43. axios({
  44. method: 'post',
  45. url: '/user/12345',
  46. data: {
  47. firstName: 'Fred',
  48. lastName: 'Flintstone'
  49. }
  50. });
  51. // GET request for remote image
  52. axios({
  53. method:'get',
  54. url:'http://bit.ly/2mTM3nY',
  55. responseType:'stream'
  56. })
  57. .then(function(response) {
  58. response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  59. });
  60. ### Creating an instance
  61. const instance = axios.create({
  62. baseURL: 'https://some-domain.com/api/',
  63. timeout: 1000,
  64. headers: {'X-Custom-Header': 'foobar'}
  65. });
  1. var retryFn = require('retry-function');
  2. var myFunc = function (cb) {return process.nextTick(cb(null, 'foo'))},
  3. myCallback = function (err, data) {};
  4. retryFn({
  5. method: myFunc,
  6. options: {
  7. retries: 5
  8. }
  9. }, myCallback);
  10. options is a JS object that can contain any of the following keys:
  11. - retries: The maximum amount of times to retry the operation. Default is 10.
  12. - factor: The exponential factor to use. Default is 2.
  13. - minTimeout: The number of milliseconds before starting the first retry. Default is 1000.
  14. - maxTimeout: The maximum number of milliseconds between two retries. Default is Infinity.
  15. - randomize: Randomizes the timeouts by multiplying with a factor between 1 to 2. Default is false.
  16. ### Conditional Retry(重试条件)
  17. retryFn({
  18. method: myFunc,
  19. shouldRetry: function (err) { return err.code >= 500; }
  20. }, myCallback);
  21. ### Additional args(额外的参数)
  22. You may need to pass additional arguments to your method. You may do so by adding an arguments array to the retryFn config. The same arguments will be passed to each execution of the method.
  23. retryFn({
  24. method: myFunc,
  25. arguments: ['foo']
  26. }, myCallback);
  1. rateLimit(limitCount, limitInterval, function)
  2. config:
  3. - limitCount - the number of times per limitInterval to limit execution of function
  4. - limitInterval - the duration of time during which to limit execution of function specified in ms
  5. - function - the function which should be rate limited
  6. Example:
  7. var rateLimit = require('function-rate-limit');
  8. // limit to 2 executions per 1000ms
  9. var start = Date.now()
  10. var fn = rateLimit(2, 1000, function (x) {
  11. console.log('%s ms - %s', Date.now() - start, x);
  12. });
  13. for (var y = 0; y < 10; y++) {
  14. fn(y);
  15. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注