提交 c80dc20c 编写于 作者: D David Graham

Merge pull request #7 from github/body-used

Allow body to be consumed only once
......@@ -61,6 +61,13 @@
})
}
function consumed(body) {
if (body.bodyUsed) {
return new Promise.reject(new TypeError('Body already consumed'))
}
body.bodyUsed = true
}
function Body() {
this.body = null
this.bodyUsed = false
......@@ -70,7 +77,8 @@
}
this.blob = function() {
return Promise.resolve(new Blob([this.body]))
var rejected = consumed(this)
return rejected ? rejected : Promise.resolve(new Blob([this.body]))
}
this.formData = function() {
......@@ -78,6 +86,11 @@
}
this.json = function() {
var rejected = consumed(this)
if (rejected) {
return rejected
}
var body = this.body
return new Promise(function(resolve, reject) {
try {
......@@ -89,7 +102,8 @@
}
this.text = function() {
return Promise.resolve(this.body)
var rejected = consumed(this)
return rejected ? rejected : Promise.resolve(this.body)
}
return this
......
......@@ -137,3 +137,33 @@ asyncTest('post sets content-type header', 1, function() {
start()
})
})
asyncTest('rejects blob promise after body is consumed', 1, function() {
fetch('/hello').then(function(response) {
response.blob()
return response.blob()
}).catch(function(error) {
ok(error instanceof TypeError, 'Promise rejected after body consumed')
start()
})
})
asyncTest('rejects json promise after body is consumed', 1, function() {
fetch('/json').then(function(response) {
response.json()
return response.json()
}).catch(function(error) {
ok(error instanceof TypeError, 'Promise rejected after body consumed')
start()
})
})
asyncTest('rejects text promise after body is consumed', 1, function() {
fetch('/hello').then(function(response) {
response.text()
return response.text()
}).catch(function(error) {
ok(error instanceof TypeError, 'Promise rejected after body consumed')
start()
})
})
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册