有没有办法将 [[Promise Result]] 保存为变量?

Tu-*_* Le 6 javascript promise ecmascript-6

我正在尝试访问 [[Promise Results]] 并将其保存为变量。最终目标我只想要 .then 语句的结果并将其用于其他函数。如果有其他更好的方法,请告诉我,我是 JavaScript 新手,所以如果你能向我解释它而不仅仅是转储代码,那就太棒了。提前致谢 这是获取请求

function currentloginid() {
    return fetch('http://localhost/gaq/api/api.php?action=userid', {
       method: 'GET',
    })
    .then(function(response) {
        return response.json();
    })
    .then(function(data) {
        var userid = JSON.parse(data);
        console.log(userid);
        return userid;
    })
}
Run Code Online (Sandbox Code Playgroud)

下面的代码是当我在另一个函数中控制台记录该函数时的代码

Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: 1
Run Code Online (Sandbox Code Playgroud)

Omr*_*iya 14

有 3 种方法可以解决这个问题:

  1. 由于您返回了一个承诺,因此请使用.then来获取返回值。

function currentloginid() {
  return fetch('http://localhost/gaq/api/api.php?action=userid', {
      method: 'GET',
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      var userid = JSON.parse(data);
      console.log(userid);
      return userid;
    })
}

currentloginid().then(value => console.log(value));
Run Code Online (Sandbox Code Playgroud)

  1. .then在您已有的其中之一中,将外部变量设置为该值。但是这个解决方案并不好,因为您可能会遇到myValue未设置的情况。

let myValue;

function currentloginid() {
  return fetch('http://localhost/gaq/api/api.php?action=userid', {
      method: 'GET',
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      var userid = JSON.parse(data);
      console.log(userid);
      myValue = userid
      return userid;
    })
}

currentloginid();
console.log(myValue);
Run Code Online (Sandbox Code Playgroud)

  1. 使用语法糖async await“等待”返回值。我认为这种方法更具可读性且易于使用(在幕后它与选项 1 相同)。
function currentloginid() {
  return fetch('http://localhost/gaq/api/api.php?action=userid', {
      method: 'GET',
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      var userid = JSON.parse(data);
      console.log(userid);
      return userid;
    })
}

console.log(await currentloginid());
Run Code Online (Sandbox Code Playgroud)