4

我正在尝试访问 [[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;
    })
}

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

Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: 1
4

3 回答 3

9

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

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

  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());
于 2020-10-02T01:27:43.837 回答
1

async/await您可以直接使用并返回数据(用户 ID),而不是承诺链。

const currentloginid = async () => {
  const response = await fetch('http://localhost/gaq/api/api.php?action=userid')

  const data = await response.json()
  
  //console.log(JSON.parse(data))

  return JSON.parse(data)
}
于 2020-10-02T01:21:32.423 回答
0

你可以根据需要多次调用 then() 。

将函数返回的 Promise 存储在变量中允许您在then()需要时在该变量上使用

function currentloginid() {
  return fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(response => response.json())
}

const storedPromise = currentloginid();
console.log('No delay')
storedPromise.then(({name, id})=> console.log({name, id}))

setTimeout(()=>{
  console.log('After delay, same promise')
  storedPromise.then(({name, id})=> console.log({name, id}))
}, 2000)

于 2020-10-02T01:39:22.013 回答