获取 JavaScript 异步函数返回值的笔记

wrong action

function asyncfunc() { let ret = 100; setTimeout(() => { return ret; }, 1000) } let ret = asyncfunc() console.log(ret) // undefined

callback

function asyncfunc(callback) { let ret = 100; setTimeout(() => { callback(ret) }, 1000) } function callback(ret) { // 处理异步获取的数据 console.log(ret) } asyncfunc(callback)

promise

function asyncfunc() { let ret = 100 return new Promise(function(resolve) { setTimeout(() => { resolve(ret) }, 1000) }) } asyncfunc().then(value => { // 处理异步获取的数据 console.log(value) })

generator

function asyncfunc() { let ret = 100 setTimeout(() => { it.next(ret) }, 1000) } function *gen() { let ret = yield asyncfunc() // 处理异步获取的数据 console.log(ret) } let it = gen() it.next()

generator + promise

function asyncfunc() { let ret = 100 return new Promise(resolve => { setTimeout(() => { resolve(ret) }, 1000) }) } function *gen() { let ret = yield asyncfunc() // 处理异步获取的数据 console.log(ret) } let it = gen() it.next().value.then(value => { it.next(value) })

 

async/await

function asyncfunc() { let ret = 100 return new Promise(resolve => { setTimeout(() => { resolve(ret) }, 1000) }) } (async function() { let ret = await asyncfunc() // 处理异步获取的数据 console.log(ret) })()

所有的异步代码必须写在 new Promise 的逻辑里

如果你想获取一个 async 函数的结果,你需要使用 Promise 的 then 语法:(async 函数的执行结果会自动变成一个 Promise)

async function doubleAndAdd(a, b) { a = await doubleAfter1Sec(a) b = await doubleAfter1Sec(b) return a + b } function doubleAfter1Sec(param) { return new Promise(resolve => { setTimeout(() => resolve(param * 2), 1000) }) } doubleAndAdd(1, 3).then(console.log) // 8

在上面的例子中,我们显示地调用了 await 两次,因为每次都等待了 1 秒钟,因此总计两秒钟。现在,我们可以使用 Promise.all 函数来让他们并行处理。

async function doubleAndAdd(a, b) { [a, b] = await Promise.all([doubleAfter1Sec(a), doubleAfter1Sec(b)]) return a + b } function doubleAfter1Sec(param) { return new Promise(resolve => { setTimeout(() => resolve(param * 2), 1000) }) } doubleAndAdd(1, 3).then(console.log) // 8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值