繁体   English   中英

如何使用 setInterval 调用异步函数?

[英]How do you call a asynchronous function using setInterval?

我得到一个随机词,然后用这个词生成一个 GIF。 我这里的代码只运行一次。 我希望它在不刷新浏览器的情况下生成另一个单词并获取另一个图像。

所以,我使用了setInerval(); 通过传递使用fetch()获取图像的函数

const section = document.getElementById('main');
const text = document.querySelector('.word');

let wordurl = 'https://random-word-api.herokuapp.com/word?number=1&swear=0';
let giphyapikey = '62urPH2PxR2otT2FjFFGNlvpXmnvRVfF';

//Setinterval

setInterval(wordgif(), 5000);


//make WordGIF call
function wordgif() {
    wordGIF().then(results => {
        text.innerHTML = results.word;
        section.innerHTML = `<img src=${results.imgurl}>`;
    }).catch(err => console.error(err))
}
//Async/await
async function wordGIF() {
    let fetchword = await fetch(wordurl);
    let word = await fetchword.json();
    console.log(word)
    let fetchgif = await fetch(`http://api.giphy.com/v1/gifs/search?q=${word}&api_key=${giphyapikey}&limit=1`);
    let gif = await fetchgif.json();
    console.log(gif)
    let imgurl = gif.data[0].images['fixed_height_small'].url;
    return {
        word: word,
        imgurl: imgurl
    }
}

据我的理解不应该setInterval(wordgif(), 5000); 每 5 秒调用一次并生成一个新单词和图像? 你如何用异步函数设置间隔?

setInterval(wordgif(), 5000);

此代码将调用wordgif ,然后将该函数的结果传递给setInterval 它相当于:

const wordgifResult = wordgif();
setInterval(wordgifResult, 5000);

由于wordgif不返回值,因此调用setInterval没有实际效果。

如果您希望setInterval调用wordgif ,则只需传递对该函数的引用作为参数:

setInterval(wordgif, 5000);

我已经稍微更新了你的代码。

  • 您应该定期清除间隔。
  • 您不需要从async函数返回任何内容,只需在函数内部执行您想要执行的操作即可。
  • 在渲染之前必须检查gif文件是否可用。

 const section = document.getElementById('main'); const text = document.querySelector('.word'); let wordurl = 'https://random-word-api.herokuapp.com/word?number=1&swear=0'; let giphyapikey = '62urPH2PxR2otT2FjFFGNlvpXmnvRVfF'; wordGIF(); // can load first gif before interval //Setinterval let interval; if (interval) clearInterval(interval); interval = setInterval(wordGIF, 5000); //Async/await async function wordGIF() { let fetchword = await fetch(wordurl); let word = await fetchword.json(); let fetchgif = await fetch(`https://api.giphy.com/v1/gifs/search?q=${word}&api_key=${giphyapikey}&limit=1`); let gif = await fetchgif.json(); console.log('Gif available: ' + (gif && Object.keys(gif.data).length > 0)); if (gif && Object.keys(gif.data).length > 0) { let imgurl = gif.data[0].images['fixed_height_small'].url; text.innerHTML = word; section.innerHTML = `<img src=${imgurl}>`; } }
 .as-console-wrapper { max-height: 20px !important; }
 <div id="main"></div> <div class="word"></div>

暂无
暂无

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

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