开发手册 欢迎您!
软件开发者资料库

JavaScrip(JS) 使用异步(async/await)函数方法 setTimeout实现定时递归调用

本文主要介绍JavaScrip(JS)中,使用 setTimeout或await sleep通过异步(async)函数方法实现递归调用和async 和 await的基本含义及使用,以及相关的示例代码。

1、async 和 await的基本含义及使用

async 是一个修饰符,async 定义的函数会默认的返回一个Promise对象resolve的值,因此对async函数可以直接进行then操作,返回的值即为then方法的传入函数。

例如,

//  async基础用法测试async function fun0() {    console.log(1)    return 1}fun0().then( x => { console.log(x) })  //  输出结果 1, 1,async function funa() {    console.log('a')    return 'a'}funa().then( x => { console.log(x) })  //  输出结果a, a,async function funo() {    console.log({})    return {}}funo().then( x => { console.log(x) })   // 输出结果 {}  {}async function funp() {    console.log('Promise')    return new Promise(function(resolve, reject){        resolve('Promise')    })}funp().then( x => { console.log(x) })   // 输出promise  promise

await 也是一个修饰符,await 关键字 只能放在 async 函数内部, await关键字的作用 就是获取 Promise中返回的内容, 获取的是Promise函数中resolve或者reject的值。如果await 后面并不是一个Promise的返回值,则会按照同步程序返回值处理。

例如,

//  await 关键字 只能放在 async 函数内部, await关键字的作用 就是获取 Promise中返回的内容, 获取的是Promise函数中resolve或者reject的值// 如果await 后面并不是一个Promise的返回值,则会按照同步程序返回值处理,为undefinedconst bbb = function(){ return 'string'}async function funAsy() {   const a = await 1   const b = await new Promise((resolve, reject)=>{        setTimeout(function(){           resolve('time')        }, 3000)   })   const c = await bbb()   console.log(a, b, c)}funAsy()  //  运行结果是 3秒钟之后 ,输出 1, time , string,// 如果不使用promise的方法的实现function log2(time) {   setTimeout(function(){       console.log(time)       return 1    }, time)}async function fun1() {    const a = await log2(5000)    const b = await log2(10000)    const c = log2(2000)    console.log(a)    console.log(1)}fun1()

2、使用setTimeout实现

async function ticker(minutes) {
try {
const res = await coingecko.global()
const { market_cap_percentage } = res.data.data
dominance = { btc: market_cap_percentage.btc, eth: market_cap_percentage.eth }
console.log({ dominance })
} catch (ex) {
console.log(ex.message)
} finally {
setTimeout(ticker, minutes * 60 * 1000, minutes);
}
}
setTimeout(ticker, minutes * 60 * 1000, 1);

3、使用Promise和setTimeout实现

async function sleep(ms) {  return new Promise(res => setTimeout(res, ms));}
(async function ticker (minutes) { do { await sleep(minutes * 60 * 1000); await loadData(); } while (true); async function loadData() { try { const res = await coingecko.global() const { market_cap_percentage } = res.data.data dominance = { btc: market_cap_percentage.btc, eth: market_cap_percentage.eth } } catch (err) { console.error(ex.message); } }})(1)