尝试从 API 中获取随机引用,但我只获得了包含它的 Promise。我该如何进一步重组?

问题描述 投票:0回答:1

这是代码:

function getRandomQuote () {
    return fetch(random_quote_api_url)
        .then(response => response.json())
        .then(data => data)
}

async function renderQuote () {

    quoteDisplay.innerHTML = '';

    const quote = await getRandomQuote();
    
    quote.split('').forEach(character => {
        const characterSpan = document.createElement('span');
        characterSpan.innerText = character;
        quoteDisplay.append(characterSpan);
    })

    quoteInput.value = null;

    startTimer();
}

我得到:

Promise

result: {_id: "qVYnD_eLg5", content: "TV and the Internet are good because they keep stu…people from spending too much time out in public.", author: "Douglas Coupland", tags: ["Technology"], authorSlug: "douglas-coupland", …}

status: "resolved"

我想要得到的是:“电视和互联网很好,因为它们可以让人们避免在公共场合花费太多时间。”

承诺原型

尝试重写 getRandomQuote 函数:data=> data.result。尝试添加另一个等待 getRandomQuote。

javascript promise
1个回答
0
投票

您的代码是如此复杂,重写是比猜测确切错误更好的建议。请参阅这些猜测的评论。

所有这些等待、异步和函数都可以在这几行中完成

let tId = setInterval(() => {
  fetch(random_quote_api_url)
    .then(response => response.json())
    .then(data => {
      quoteDisplay.innerHTML = [...data.quote] // assuming { "quote": "string of words" }
        .map(character => `<span>${character}</span>`)
        .join('');
       // startTimer(); // assuming some typing widget?
    })
}, 10000)
© www.soinside.com 2019 - 2024. All rights reserved.