繁体   English   中英

是否可以仅通过承诺(无异步/等待)从 fetch 返回响应

[英]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方法返回一个Promise ,在您的情况下,它返回一个Promise ,该 Promise 使用response.text()解析的任何内容解析。 注意: response.text()也返回一个Promise

返回另一个待处理的 Promise 对象,然后返回的 Promise 的解析/拒绝将在处理程序返回的 Promise 的解析/拒绝之后。 此外,then 返回的 promise 的已解析值将与处理程序返回的 promise 的已解析值相同。 来源

现在,你需要从你的函数中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.log(res instanceof Promise); // true return res; }) } callWs2().then(console.log);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM