是否可以以诺言来返回响应(没有异步/等待)

发布于 2025-01-28 07:52:38 字数 357 浏览 1 评论 0原文

为什么这不起作用(我借给 >):

  callWs2 = function(){
    let url = 'https://jsonplaceholder.typicode.com/posts/1';
    fetch(url)
    .then(function(response) {
      return response.text();
    })
  }

  console.log(callWs2());

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());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦明 2025-02-04 07:52:38

。然后方法返回Promise,在您的情况下,它将返回Promise,该可以通过任何response> response..text()解决。注意:response.text()还返回Promise

返回另一个未决的承诺对象,当时归还的承诺的决议/拒绝将在处理者返回的承诺的解决/拒绝之后。同样,当时返回的承诺的解析价值将与处理程序返回的承诺的解决价值相同。

现在,您需要返回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);

.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);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文