javascript - 承诺总是未定义
问题描述
我正在尝试调用 API 并使用结果,但承诺结果总是以未定义的形式返回。
我认为这应该是直截了当的,但我是新的承诺,我花了很多时间试图解决这个问题,但没有任何运气。我试过很多版本。我想要
- 调用 API
- API 将返回我对其中的一组数字感兴趣的 JSON
- 解析 JSON 以获取该数组
- 在另一个函数中使用数组来做某事
最初我有这两个功能
//Get the references
function getReferences(articleID) {
var request = new XMLHttpRequest();
request.open("get", "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi?dbfrom=pubmed&linkname=pubmed_pubmed_refs&retmode=json&id=" + articleID + "&api_key=0&tool=my_tool2&email=my_email@example.com", false);
request.send();
var obj = JSON.parse(request.responseText);
return obj.linksets[0].linksetdbs[0].links;
}
//use the references
function useReferences(startingArticleID) {
var references = getReferences(startingArticleID);
// do something with the array "references"
}
这很好用,除了有时getReferences
会在 API 调用完成之前尝试解析。所以我修改了代码看起来像这样(使用 Axios 尝试帮助 API 调用)
async function getReferences(articleID) {
let json = await axios.get("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi? dbfrom=pubmed&linkname=pubmed_pubmed_refs&retmode=json&id=" + articleID + "&api_key=0&tool=my_tool2&email=my_email@example.com");
return json;
}
async function useReferences(startingArticleID) {
let references = await getReferences(startingArticleID);
//do something with the array references
}
但references
总是undefined
以待处理状态返回。我阅读并尝试过,.then()
但承诺的价值仍然是undefined
.
解决方案
推荐阅读
- android - 使用 DiffUtil 和 AsyncListDiffer 更新 RecyclerView 不起作用
- mongodb - 如何使用 Azure Cosmos DB API for MongoDB(3.6 版)的数据库命令重命名数组中的字段?
- terminal - 如何在终端“损坏”时修复终端,吞下换行符
- pyspark - 如何知道使用 azure-cosmosdb-spark 消耗的请求单元 (RU) 的数量
- excel - 尝试访问数组时下标超出范围
- r - 带有 gtsummary 包的加权 Cox 回归模型汇总表
- ruby - 生成增加的随机数轨道
- linux - 如何删除文件1中不在文件2中的
- telegram - 开始按钮中缺少电报深度链接开始参数
- python - 无论你输入什么,我总是得到 ID 不在列表中