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());
.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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.