'is it possible to return response from fetch with just promise (no async/await)
Why this doesn't work (I borrowed to https://jsfiddle.net/xlanglat/tyh6jjpy/):
callWs2 = function(){
let url = 'https://jsonplaceholder.typicode.com/posts/1';
fetch(url)
.then(function(response) {
return response.text();
})
}
console.log(callWs2());
Solution 1:[1]
.then method returns a Promise and in your case it returns a Promise that resolves with whatever response.text() resolves with. Note: response.text() also returns a Promise.
Returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by then will be the same as the resolved value of the promise returned by the handler. Source.
Now, you need to return this Promise from your function.
And finally when you're calling the function you need to chain it with .then because the function returns a Promise.
function callWs2() {
let url = 'https://jsonplaceholder.typicode.com/posts/1';
return fetch(url)
.then(function(response) {
const res = response.text();
console.log(res instanceof Promise); // true
return res;
})
}
callWs2().then(console.log);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
