Entry of the new company, just began to maintain old projects, there are many jQuery code, now need to add a new demand, the need to perform three parallel asynchronous operation, loading the generic template, load data, layui load plug-in modules, tells his story just before reading nodejs studied the partial function, just use and familiarize yourself with the right now.

  • Compare the low approach
Layui.use (['laytpl'], function () {layui.laytpl = layui.laytpl loadData('url', function (data) { loadHtml('templateAddress', renderHtml(tpl,data)) }) })Copy the code
  • Use partial function optimization
function render (collectDone) { let cache = { laytpl: null, data: null, html: '' } function cacheFill () { for (let key in cache) { if (! cache[key]) { return false } } return true } return function (key, data) { cache[key] = data if (cacheFill()) { collectDone(cache) } } } let renderCollect = render(renderFn) layui.use(['laytpl'], () => renderCollect('laytpl', layui.laytpl)) loadData('url', (data) => renderCollect('data', data)) loadHtml('htmlPath', html => renderCollect('html', html))Copy the code
The essence of a partial function is to create a function (renderCollect) that can call another part of the render parameter or variable has been preset. In fact, this function wrapper function is widely used in JS, and will be updated when there is time
Promise.all([PromiseList]) is a PromiseList that contains a Promise instance