简体   繁体   English

JavaScript,承诺{<pending> }

[英]JavaScript, Promise {<pending>}

async function db(path){
  const res = await fetch('data.json');
  const data = await res.json();
  return data[path];
}

console.log(db("name"));

how can i fix the Promise {pending} I am trying to get Global Access to my database json file from anywhere in my code is this right way or there is a better way ?我如何修复 Promise {pending} 我试图从我的代码中的任何位置全局访问我的数据库 json 文件是正确的方法还是有更好的方法?

The problem is that you have an async function that returns a promise, but you call it in a not async way.问题是您有一个返回承诺的异步函数,但您以非异步方式调用它。 What you should simply do is add an await before your call:你应该做的是在你打电话之前添加一个等待:

async function db(path){
  const res = await fetch('data.json');
  const data = await res.json();
  return data[path];
}

console.log(await db("name"));

The return of the function simply returns another promise.函数的返回只是返回另一个承诺。 So you can modify your function like this-所以你可以像这样修改你的函数 -

async function db(){
  const res = await fetch('data.json');
  const data = await res.json();
  return data;
}

db().then(data => console.log(data['name']);

Note: You should not return anything from a async function.注意:您不应从异步函数返回任何内容。 You should do what you want inside the funciton你应该在函数内做你想做的事

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

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