如何读取 PROMISE .then 函数之外的对象

How to read an object outside a PROMISE .then function

我试图访问 PROMISE .then() 方法之外的对象,但是当我在范围之外调用该函数时,我的对象变得未定义。

我的应用是 chrome 扩展。

函数-

function get_API (){
  let url = 'http://example.com'
  fetch(url)
      .then(response => response.json())
      .then (data => { 
        console.log(data)
        return data
      })
    }

输出良好,正在将 json 从 API url 打印到控制台。

但是当试图在 .then() 范围之外到达它时:

let x = get_API()
console.log(x)

输出未定义


编辑: bt Dusan Malusev 提供的答案是我需要在获取之前添加 return 。现在它正在工作。

工作代码:

function get_API (){
  return fetch('www.example.com')
      .then(response => response.json())
      .then (data => { 
        console.log(data)
        return data
      })
      
}

你应该return这样的承诺

function get_API() {
  let url = "http://example.com";
  return fetch(url)
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
      return data;
    });
}

然后 await 响应,在 async 函数中

async function asynFunction() {
  const x = await get_API();
  console.log(x);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

要了解 promises 和 callbacks 你应该看看这个演讲 Event Loop。 Javascript事件循环一开始运行都是同步代码,也就是说 console.log 运行s 在你的任何承诺代码之前,这就是为什么 x 是 undefined.then(...) 内的回调将在所有同步代码和所有回调之后 运行 (回调和承诺之间有区别) 你可以把 promise 想成你把某事推迟到 运行 以后。

async => await 只是 promises 的语法糖,它让我们的 javascript 看起来像同步代码,但它是异步的。我对 promises 所说的一切在 async => await 中仍然有效(它们只是 promises)

async function asynFunction() {
   const x = await get_API();
   console.log(x);
}

此函数等同于:

function f() {
   get_API().then(data => {
        let x = data; 
        console.log(x));
   })
}

不像:

function f() {
   let x;
   get_API().then(data => x = data)
   console.log(x)
}

回调和承诺的资源:

Async JS Crash Course - Callbacks, Promises, Async Await

MDN Prmises

MDN Callbacks

JavaScript 和其他语言不一样,你需要绕过事件循环。并以“JavaScript方式”做所有事情。

你问题的答案:

   function get_API() {
       let url = "http://example.com";
       return fetch(url)
          .then((response) => response.json())
          .then((data) => {
              console.log(data);
              return data;
          });
   }

fetch 函数默认有两个 promise,首先从服务器获取响应,其次用于格式化数据。如果你想像这样使用它

function f() {
   get_API().then(data => {
        let x = data; 
        console.log(x));
   })
}

您的 api 函数必须更改

  function get_API() {
       let url = "http://example.com";
       return fetch(url)
          .then((response) => response.json());
   }

现在你的函数 returns 一个承诺,你可以在另一个函数中使用 .then 并获取数据。