Js异步编程

2022-02-25 19:04:15 浏览数 (1)

回调函数

代码语言:javascript复制
function say(callback) {
    setTimeout(() => {
        console.log('11111')
        callback()
    }, 1000)
}
say(() => {
    console.log('2222')
})

Promise

代码语言:javascript复制
new Promise(function (resolve, reject) {
    setTimeout(() => {
        console.log('11111')
        resolve()
    }, 1000)
}).then(() => {
    console.log('2222')
})

async/await

代码语言:javascript复制
async function f1() {
    var res = await new Promise(function (resolve, reject) {
        setTimeout(() => {
            console.log('11111')
            resolve('2222')
        }, 1000)
    })
    console.log(res)
}
f1()

0 人点赞