Почему это не работает (я позаимствовал https://jsfiddle.net/xlanglat/tyh6jjpy/):
callWs2 = function(){
let url = 'https://jsonplaceholder.typicode.com/posts/1';
fetch(url)
.then(function(response) {
return response.text();
})
}
console.info(callWs2());
Метод .then
возвращает Promise
, и в вашем случае он возвращает Promise
, который разрешается с тем, с чем разрешается response.text()
. Примечание: response.text()
также возвращает 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.
Теперь вам нужно return
это Promise
из вашей функции.
И, наконец, когда вы вызываете функцию, вам нужно связать ее с .then
, потому что функция возвращает Promise
.
function callWs2() {
let url = 'https://jsonplaceholder.typicode.com/posts/1';
return fetch(url)
.then(function(response) {
const res = response.text();
console.info(res instanceof Promise); // true
return res;
})
}
callWs2().then(console.info);
так что вы не можете остановить обещание и просто получить значение?
Вам нужен
return
вместоcallWs2
. Обратный вызов в.then()
этого не сделает.