@JunQiu
2018-09-18T17:52:49.000000Z
字数 4317
阅读 1190
summary_2018/06
language_node
npm
//some test:
const fc=require('fetch')
async function test () {
const data=await Promise.resolve('1111')
console.log('data:'+data)
return 'aaa'
}
/*
console.log(test())
直接调用async返回promise对象,async函数中的异步操作
返回值:
Promise { <pending> } //函数直接返回promise对象
data:1111 //await完成后
*/
/*
async function test2(){
a=await test()
console.log(a)
}
test2()
返回值:等待promis对象完成后返回
data:1111
aaa
*/
结论
npm fetch和axios
### Fetch from URL
fetch.fetchUrl(url [, options], callback)
- url is the url to fetch
- options is an optional options object
- callback is the callback to run - callback(error, meta, body)
### Streaming
fetch.FetchStream(url [, options]) -> Stream
- url is the url to fetch
- options is an optional options object
### options
- maxRedirects how many redirects allowed, defaults to 10
- headers optional header fields, in the form of {'Header-Field':'value'}
- maxResponseLength maximum allowd length for the file, the remainder is cut off. Defaults to Infinity
- method defaults to GET
- payload request body
- cookies an array of cookie definitions in the form of ['name=val']
- timeout set a timeout in ms
### example
options = {
headers:{
"X-My-Header": "This is a custom header field"
}
}
options = {
cookies: ["name=value", "key=value; path=/; secure"]
}
# Piping to file(FetchStream is a readable Stream )
out = fs.createWriteStream('file.html');
new FetchStream("http://www.example.com/index.php").pipe(out);
### Example
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
## we can use promise.all
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
### axios(config)
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// GET request for remote image
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
### Creating an instance
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
var retryFn = require('retry-function');
var myFunc = function (cb) {return process.nextTick(cb(null, 'foo'))},
myCallback = function (err, data) {};
retryFn({
method: myFunc,
options: {
retries: 5
}
}, myCallback);
options is a JS object that can contain any of the following keys:
- retries: The maximum amount of times to retry the operation. Default is 10.
- factor: The exponential factor to use. Default is 2.
- minTimeout: The number of milliseconds before starting the first retry. Default is 1000.
- maxTimeout: The maximum number of milliseconds between two retries. Default is Infinity.
- randomize: Randomizes the timeouts by multiplying with a factor between 1 to 2. Default is false.
### Conditional Retry(重试条件)
retryFn({
method: myFunc,
shouldRetry: function (err) { return err.code >= 500; }
}, myCallback);
### Additional args(额外的参数)
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.
retryFn({
method: myFunc,
arguments: ['foo']
}, myCallback);
rateLimit(limitCount, limitInterval, function)
config:
- limitCount - the number of times per limitInterval to limit execution of function
- limitInterval - the duration of time during which to limit execution of function specified in ms
- function - the function which should be rate limited
Example:
var rateLimit = require('function-rate-limit');
// limit to 2 executions per 1000ms
var start = Date.now()
var fn = rateLimit(2, 1000, function (x) {
console.log('%s ms - %s', Date.now() - start, x);
});
for (var y = 0; y < 10; y++) {
fn(y);
}