【问题标题】:I want to await a function to complete then run another function我想等待一个函数完成然后运行另一个函数
【发布时间】:2022-11-17 14:28:45
【问题描述】:
const arr = ['a' , 'b' ,'c', 'd']

const func = async () => {

let i = 0
let interval = setInterval(() => {
    let com = arr[i++ % arr.length]
    console.log(com)
    if (i === 4 ) {
        clearInterval(interval)
    }
}, 2000)
}

const another_func = ()=>{
    console.log('logic')
}

const main = async ()=>{
await func()
another_func()
}
main()

// When i run this problem "logic" gets printed before all the elements of array

// When i run this problem "logic" gets printed before all the elements of array I want to print all the elements of array and then i want to run the another function and print the logic

【问题讨论】:

  • 您应该显式返回一个承诺,然后在第四个时间间隔调用回调。

标签: javascript arrays async-await es6-promise


【解决方案1】:

使用异步 - 仅在您的主要功能中等待,将其从第一个功能中删除,然后它将起作用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    相关资源
    最近更新 更多