是否有可能 return 只用 promise 从 fetch 响应(没有 async/await)

is it possible to return response from fetch with just promise (no async/await)

为什么这行不通(我借给了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 方法 returns a Promise 并且在您的情况下它 returns a Promise 用任何 response.text() 解析。注:response.text()也returns一个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 链接它,因为函数 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);