美文网首页前端开发那些事儿每天学一点Vue3ES6的基础知识
promise 、await 和 async 彻底告别回调地狱

promise 、await 和 async 彻底告别回调地狱

作者: 自然框架 | 来源:发表于2021-09-06 12:36 被阅读0次

果然是越用越熟练,上次对于 await 和 async 还比较模糊,现在熟悉多了。

先用 promise 代替回调函数

第一次听说 promise 还是因为 axios,一介绍 axios 就会提及promise,不懂咋办?学呗。
于是恶补基础知识。

先掌握基本用法,然后就可以去封装基础功能了,比如indexedDB的访问,webSQL的访问等。

await 等待一下

一开始使用 then的方式,后来发现,简单的情况还可以,但是复杂的情况就没法看了,于是开始使用await。

然后知道了,还可以有返回值,返回值就是 then的参数,怪不得参数只能有一个呢。

forEach 的 await

  const cols = [...]
  cols.forEach(async (col, index) => {
      col.tableId = intTableId
      col.columnId = intTableId + (index + 1) * 10
      col.canNull = 0
      myLog.start(col.colName, logIndex)
      res = await service(columnId, 10, col, -2, 'meta')
      myLog.end(res.newId, logIndex)
    })

一开始这么写,但是运行后发现,只是函数内部等待了,但是遍历却没有等待,还在继续遍历。

这个就,如果不需要对应的话,那么就无所谓了,但是如果想要对应上,那么目前的办法,还是改成for循环。

for 的 await

  for (let index = 0; index < cols.length; index++) {
      const col = cols[index]
      col.tableId = intTableId
      col.columnId = intTableId + (index + 1) * 10
      col.canNull = 0
      myLog.start(col.colName, logIndex)
      res = await service(columnId, 10, col, -2, 'meta')
      myLog.end(res.newId, logIndex)
  }

改成 for 的方式,就可以在循环内部进行等待了。

async 的返回值

一开始以为 标记 async 的函数,因为被强制变成返回 promise 的实例,于是就无法设置返回值了呢,后来发现我又错了。

还是可以设置返回值的,返回值会成为 then 的参数,也就是 await 的返回值。于是我们可以套娃了。

只是容易晕的套娃。

好吧,代码写了五百多行,我也不知道套了几层。

  const _moduleId = 150
  const pagerId = 151
  /**
   * 菜单和分页,存入SQL,返回分页的 meta
   */
  const addModuleSQL = async () => {
    // 模块菜单
    myLog.newLog('模块菜单')
    let res = await service(_moduleId, 10, moduleInfo.moduleModal, -2, 'meta')
    myLog.end(res.newId)

    // 分页
    const pager = {
      moduleId: moduleInfo.moduleModal.moduleId, // 分页ID, int
      showCols: '', // 显示字段, 数组
      query: '', // 查询条件, 对象
      pageSize: 10, // 一页记录数, int
      pageTotal: 100, // 总记录数, int
      pageIndex: 1, // 第几页, int
      OrderColumns: 'id', // 排序字段, 对象
      fixedQuery: 'isDel = 0', // 固定查询条件, 对象
      fristQuery: '' // 首次查询条件, 对象
    }
    myLog.newLog('列表的分页')
    res = await service(pagerId, 10, pager, -2, 'meta')
    myLog.end(res.newId)

    // 返回模块的分页信息
    return pager
  }

使用

  const setMeta = async () => {
    const newModuleMeta = { moduleId: moduleInfo.moduleModal.moduleId }
    newModuleMeta.pager = await addModuleSQL()
    newModuleMeta.button = await addButtonSQL()
    newModuleMeta.find = await addFindSQL()
    newModuleMeta.grid = await addGridSQL()
    newModuleMeta.forms = await addFormSQL()
    ... 
    return newModuleMeta 
  }

这样就可以无限套娃了,如果你喜欢的话。

相关文章

网友评论

    本文标题:promise 、await 和 async 彻底告别回调地狱

    本文链接:https://www.haomeiwen.com/subject/ycpewltx.html