栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

等待仅在异步功能中有效

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

等待仅在异步功能中有效

错误不是指

myfunction
而是
start

async function start() {   ....   const result = await helper.myfunction('test', 'test');}

// My functionconst myfunction = async function(x, y) {  return [    x,    y,  ];}// Start functionconst start = async function(a, b) {  const result = await myfunction('test', 'test');  console.log(result);}// Call startstart();


我利用这个问题的机会来告诉你一个已知的反模式的使用

await
方法:
return await


错误

async function myfunction() {  console.log('Inside of myfunction');}// Here we wait for the myfunction to finish// and then returns a promise that'll be waited for aswell// It's useless to wait the myfunction to finish before to return// we can simply returns a promise that will be resolved later// useless async hereasync function start() {  // useless await here  return await myfunction();}// Call start(async() => {  console.log('before start');  await start();  console.log('after start');})();

正确

async function myfunction() {  console.log('Inside of myfunction');}// Here we wait for the myfunction to finish// and then returns a promise that'll be waited for aswell// It's useless to wait the myfunction to finish before to return// we can simply returns a promise that will be resolved later// Also point that we don't use async keyword on the function because// we can simply returns the promise returned by myfunctionfunction start() {  return myfunction();}// Call start(async() => {  console.log('before start');  await start();  console.log('after start');})();

另外,要知道有一个

return await
正确且重要的特殊情况:(使用try / catch)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/368596.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号