robstoll
03/12/2018, 8:04 AMnew Promise(function(resolve, reject) {
resolve({
ok: true,
text: function() {
return new Promise(function(resolve, reject){ resolve("{json: 'body'}") })
}
})
}).then(function(response) {
return response.text().then(function(text) {
if (!response.ok) {
reject('response was not ok...')
}
return text
})
}).then(function(body){
alert(body)
})
body isn't a promise in the last then
but the string resolved from text()gildor
03/12/2018, 8:22 AMfun <T> Promise<Promise<T>>.unwrap() = then { it }
So it fixes your original sample
Or even provide something like flatMap function for promises (like then + unwrap):
// flatMap or for symmetry something like flatThen
fun <T, S> Promise<T>.flatMap(block: (T) -> Promise<S>): Promise<S> {
return then {
block(it)
}.then { it }
}
So now to fix your sample you can replace first then
with flatMap
and avoid nested Promises
Anyway, I would choose coroutines instead of chaining of promises