首页 > 解决方案 > 承诺总是未定义

问题描述

我正在尝试调用 API 并使用结果,但承诺结果总是以未定义的形式返回。

我认为这应该是直截了当的,但我是新的承诺,我花了很多时间试图解决这个问题,但没有任何运气。我试过很多版本。我想要

  1. 调用 API
    • API 将返回我对其中的一组数字感兴趣的 JSON
  2. 解析 JSON 以获取该数组
  3. 在另一个函数中使用数组来做某事

最初我有这两个功能

//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.

标签: javascriptpromise

解决方案


推荐阅读