10简化返回数据和使用es7的async语法

2023-12-25 03:48

本文主要是介绍10简化返回数据和使用es7的async语法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

es7的 async async 号称是解决回调的最终⽅案

  1. 在⼩程序的开发⼯具中,勾选es6转es5语法
  2. 下载facebook的regenerator库中的regenerator/packages/regenerator-runtime/runtime.js(由于github经常上不去,我把代码放在最后)
  3. 在⼩程序⽬录下新建⽂件夹 lib/runtime/runtime.js lib/runtime/runtime.js ,将代码拷⻉进去
  4. 在每⼀个需要使⽤async语法的⻚⾯js⽂件中,都引⼊(不能全局引⼊)
import regeneratorRuntime from '../../lib/runtime/runtime';
//获取分类数据async getCates(){// 1 使用es7的async await来发送请求const res = await request({url:"/categories"});this.Cates = res;//把接口数据存入到本地存储中wx.setStorageSync('cates', {time:Date.now(),data:this.Cates})// 构造左侧大菜单数据let leftMenuList = this.Cates.map(v=>v.cat_name);// 构造右侧的商品数据let rightContent = this.Cates[0].children;this.setData({leftMenuList,rightContent})},

此处this.cates = res.data.message改造成this.cates = res
在resquest中修改

export const request=(params)=>{// url:"https://api-hmugo-web.itheima.net/api/public/v1/categories"const baseUrl = "https://api-hmugo-web.itheima.net/api/public/v1"return new Promise((resolve,reject)=>{wx.request({...params,url:baseUrl+params.url,success:(result)=>{resolve(result.data.message);},fail:(err)=>{reject(err);}});})
}

runtime.js

/*** Copyright (c) 2014-present, Facebook, Inc.** This source code is licensed under the MIT license found in the* LICENSE file in the root directory of this source tree.*/var regeneratorRuntime = (function (exports) {"use strict";var Op = Object.prototype;var hasOwn = Op.hasOwnProperty;var undefined; // More compressible than void 0.var $Symbol = typeof Symbol === "function" ? Symbol : {};var iteratorSymbol = $Symbol.iterator || "@@iterator";var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";function wrap(innerFn, outerFn, self, tryLocsList) {// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;var generator = Object.create(protoGenerator.prototype);var context = new Context(tryLocsList || []);// The ._invoke method unifies the implementations of the .next,// .throw, and .return methods.generator._invoke = makeInvokeMethod(innerFn, self, context);return generator;}exports.wrap = wrap;// Try/catch helper to minimize deoptimizations. Returns a completion// record like context.tryEntries[i].completion. This interface could// have been (and was previously) designed to take a closure to be// invoked without arguments, but in all the cases we care about we// already have an existing method we want to call, so there's no need// to create a new function object. We can even get away with assuming// the method takes exactly one argument, since that happens to be true// in every case, so we don't have to touch the arguments object. The// only additional allocation required is the completion record, which// has a stable shape and so hopefully should be cheap to allocate.function tryCatch(fn, obj, arg) {try {return { type: "normal", arg: fn.call(obj, arg) };} catch (err) {return { type: "throw", arg: err };}}var GenStateSuspendedStart = "suspendedStart";var GenStateSuspendedYield = "suspendedYield";var GenStateExecuting = "executing";var GenStateCompleted = "completed";// Returning this object from the innerFn has the same effect as// breaking out of the dispatch switch statement.var ContinueSentinel = {};// Dummy constructor functions that we use as the .constructor and// .constructor.prototype properties for functions that return Generator// objects. For full spec compliance, you may wish to configure your// minifier not to mangle the names of these two functions.function Generator() {}function GeneratorFunction() {}function GeneratorFunctionPrototype() {}// This is a polyfill for %IteratorPrototype% for environments that// don't natively support it.var IteratorPrototype = {};IteratorPrototype[iteratorSymbol] = function () {return this;};var getProto = Object.getPrototypeOf;var NativeIteratorPrototype = getProto && getProto(getProto(values([])));if (NativeIteratorPrototype &&NativeIteratorPrototype !== Op &&hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {// This environment has a native %IteratorPrototype%; use it instead// of the polyfill.IteratorPrototype = NativeIteratorPrototype;}var Gp = GeneratorFunctionPrototype.prototype =Generator.prototype = Object.create(IteratorPrototype);GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor = GeneratorFunction;GeneratorFunctionPrototype[toStringTagSymbol] =GeneratorFunction.displayName = "GeneratorFunction";// Helper for defining the .next, .throw, and .return methods of the// Iterator interface in terms of a single ._invoke method.function defineIteratorMethods(prototype) {["next", "throw", "return"].forEach(function(method) {prototype[method] = function(arg) {return this._invoke(method, arg);};});}exports.isGeneratorFunction = function(genFun) {var ctor = typeof genFun === "function" && genFun.constructor;return ctor? ctor === GeneratorFunction ||// For the native GeneratorFunction constructor, the best we can// do is to check its .name property.(ctor.displayName || ctor.name) === "GeneratorFunction": false;};exports.mark = function(genFun) {if (Object.setPrototypeOf) {Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);} else {genFun.__proto__ = GeneratorFunctionPrototype;if (!(toStringTagSymbol in genFun)) {genFun[toStringTagSymbol] = "GeneratorFunction";}}genFun.prototype = Object.create(Gp);return genFun;};// Within the body of any async function, `await x` is transformed to// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test// `hasOwn.call(value, "__await")` to determine if the yielded value is// meant to be awaited.exports.awrap = function(arg) {return { __await: arg };};function AsyncIterator(generator) {function invoke(method, arg, resolve, reject) {var record = tryCatch(generator[method], generator, arg);if (record.type === "throw") {reject(record.arg);} else {var result = record.arg;var value = result.value;if (value &&typeof value === "object" &&hasOwn.call(value, "__await")) {return Promise.resolve(value.__await).then(function(value) {invoke("next", value, resolve, reject);}, function(err) {invoke("throw", err, resolve, reject);});}return Promise.resolve(value).then(function(unwrapped) {// When a yielded Promise is resolved, its final value becomes// the .value of the Promise<{value,done}> result for the// current iteration.result.value = unwrapped;resolve(result);}, function(error) {// If a rejected Promise was yielded, throw the rejection back// into the async generator function so it can be handled there.return invoke("throw", error, resolve, reject);});}}var previousPromise;function enqueue(method, arg) {function callInvokeWithMethodAndArg() {return new Promise(function(resolve, reject) {invoke(method, arg, resolve, reject);});}return previousPromise =// If enqueue has been called before, then we want to wait until// all previous Promises have been resolved before calling invoke,// so that results are always delivered in the correct order. If// enqueue has not been called before, then it is important to// call invoke immediately, without waiting on a callback to fire,// so that the async generator function has the opportunity to do// any necessary setup in a predictable way. This predictability// is why the Promise constructor synchronously invokes its// executor callback, and why async functions synchronously// execute code before the first await. Since we implement simple// async functions in terms of async generators, it is especially// important to get this right, even though it requires care.previousPromise ? previousPromise.then(callInvokeWithMethodAndArg,// Avoid propagating failures to Promises returned by later// invocations of the iterator.callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();}// Define the unified helper method that is used to implement .next,// .throw, and .return (see defineIteratorMethods).this._invoke = enqueue;}defineIteratorMethods(AsyncIterator.prototype);AsyncIterator.prototype[asyncIteratorSymbol] = function () {return this;};exports.AsyncIterator = AsyncIterator;// Note that simple async functions are implemented on top of// AsyncIterator objects; they just return a Promise for the value of// the final result produced by the iterator.exports.async = function(innerFn, outerFn, self, tryLocsList) {var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList));return exports.isGeneratorFunction(outerFn)? iter // If outerFn is a generator, return the full iterator.: iter.next().then(function(result) {return result.done ? result.value : iter.next();});};function makeInvokeMethod(innerFn, self, context) {var state = GenStateSuspendedStart;return function invoke(method, arg) {if (state === GenStateExecuting) {throw new Error("Generator is already running");}if (state === GenStateCompleted) {if (method === "throw") {throw arg;}// Be forgiving, per 25.3.3.3.3 of the spec:// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresumereturn doneResult();}context.method = method;context.arg = arg;while (true) {var delegate = context.delegate;if (delegate) {var delegateResult = maybeInvokeDelegate(delegate, context);if (delegateResult) {if (delegateResult === ContinueSentinel) continue;return delegateResult;}}if (context.method === "next") {// Setting context._sent for legacy support of Babel's// function.sent implementation.context.sent = context._sent = context.arg;} else if (context.method === "throw") {if (state === GenStateSuspendedStart) {state = GenStateCompleted;throw context.arg;}context.dispatchException(context.arg);} else if (context.method === "return") {context.abrupt("return", context.arg);}state = GenStateExecuting;var record = tryCatch(innerFn, self, context);if (record.type === "normal") {// If an exception is thrown from innerFn, we leave state ===// GenStateExecuting and loop back for another invocation.state = context.done? GenStateCompleted: GenStateSuspendedYield;if (record.arg === ContinueSentinel) {continue;}return {value: record.arg,done: context.done};} else if (record.type === "throw") {state = GenStateCompleted;// Dispatch the exception by looping back around to the// context.dispatchException(context.arg) call above.context.method = "throw";context.arg = record.arg;}}};}// Call delegate.iterator[context.method](context.arg) and handle the// result, either by returning a { value, done } result from the// delegate iterator, or by modifying context.method and context.arg,// setting context.delegate to null, and returning the ContinueSentinel.function maybeInvokeDelegate(delegate, context) {var method = delegate.iterator[context.method];if (method === undefined) {// A .throw or .return when the delegate iterator has no .throw// method always terminates the yield* loop.context.delegate = null;if (context.method === "throw") {if (delegate.iterator.return) {// If the delegate iterator has a return method, give it a// chance to clean up.context.method = "return";context.arg = undefined;maybeInvokeDelegate(delegate, context);if (context.method === "throw") {// If maybeInvokeDelegate(context) changed context.method from// "return" to "throw", let that override the TypeError below.return ContinueSentinel;}}context.method = "throw";context.arg = new TypeError("The iterator does not provide a 'throw' method");}return ContinueSentinel;}var record = tryCatch(method, delegate.iterator, context.arg);if (record.type === "throw") {context.method = "throw";context.arg = record.arg;context.delegate = null;return ContinueSentinel;}var info = record.arg;if (! info) {context.method = "throw";context.arg = new TypeError("iterator result is not an object");context.delegate = null;return ContinueSentinel;}if (info.done) {// Assign the result of the finished delegate to the temporary// variable specified by delegate.resultName (see delegateYield).context[delegate.resultName] = info.value;// Resume execution at the desired location (see delegateYield).context.next = delegate.nextLoc;// If context.method was "throw" but the delegate handled the// exception, let the outer generator proceed normally. If// context.method was "next", forget context.arg since it has been// "consumed" by the delegate iterator. If context.method was// "return", allow the original .return call to continue in the// outer generator.if (context.method !== "return") {context.method = "next";context.arg = undefined;}} else {// Re-yield the result returned by the delegate method.return info;}// The delegate iterator is finished, so forget it and continue with// the outer generator.context.delegate = null;return ContinueSentinel;}// Define Generator.prototype.{next,throw,return} in terms of the// unified ._invoke helper method.defineIteratorMethods(Gp);Gp[toStringTagSymbol] = "Generator";// A Generator should always return itself as the iterator object when the// @@iterator function is called on it. Some browsers' implementations of the// iterator prototype chain incorrectly implement this, causing the Generator// object to not be returned from this call. This ensures that doesn't happen.// See https://github.com/facebook/regenerator/issues/274 for more details.Gp[iteratorSymbol] = function() {return this;};Gp.toString = function() {return "[object Generator]";};function pushTryEntry(locs) {var entry = { tryLoc: locs[0] };if (1 in locs) {entry.catchLoc = locs[1];}if (2 in locs) {entry.finallyLoc = locs[2];entry.afterLoc = locs[3];}this.tryEntries.push(entry);}function resetTryEntry(entry) {var record = entry.completion || {};record.type = "normal";delete record.arg;entry.completion = record;}function Context(tryLocsList) {// The root entry object (effectively a try statement without a catch// or a finally block) gives us a place to store values thrown from// locations where there is no enclosing try statement.this.tryEntries = [{ tryLoc: "root" }];tryLocsList.forEach(pushTryEntry, this);this.reset(true);}exports.keys = function(object) {var keys = [];for (var key in object) {keys.push(key);}keys.reverse();// Rather than returning an object with a next method, we keep// things simple and return the next function itself.return function next() {while (keys.length) {var key = keys.pop();if (key in object) {next.value = key;next.done = false;return next;}}// To avoid creating an additional object, we just hang the .value// and .done properties off the next function object itself. This// also ensures that the minifier will not anonymize the function.next.done = true;return next;};};function values(iterable) {if (iterable) {var iteratorMethod = iterable[iteratorSymbol];if (iteratorMethod) {return iteratorMethod.call(iterable);}if (typeof iterable.next === "function") {return iterable;}if (!isNaN(iterable.length)) {var i = -1, next = function next() {while (++i < iterable.length) {if (hasOwn.call(iterable, i)) {next.value = iterable[i];next.done = false;return next;}}next.value = undefined;next.done = true;return next;};return next.next = next;}}// Return an iterator with no values.return { next: doneResult };}exports.values = values;function doneResult() {return { value: undefined, done: true };}Context.prototype = {constructor: Context,reset: function(skipTempReset) {this.prev = 0;this.next = 0;// Resetting context._sent for legacy support of Babel's// function.sent implementation.this.sent = this._sent = undefined;this.done = false;this.delegate = null;this.method = "next";this.arg = undefined;this.tryEntries.forEach(resetTryEntry);if (!skipTempReset) {for (var name in this) {// Not sure about the optimal order of these conditions:if (name.charAt(0) === "t" &&hasOwn.call(this, name) &&!isNaN(+name.slice(1))) {this[name] = undefined;}}}},stop: function() {this.done = true;var rootEntry = this.tryEntries[0];var rootRecord = rootEntry.completion;if (rootRecord.type === "throw") {throw rootRecord.arg;}return this.rval;},dispatchException: function(exception) {if (this.done) {throw exception;}var context = this;function handle(loc, caught) {record.type = "throw";record.arg = exception;context.next = loc;if (caught) {// If the dispatched exception was caught by a catch block,// then let that catch block handle the exception normally.context.method = "next";context.arg = undefined;}return !! caught;}for (var i = this.tryEntries.length - 1; i >= 0; --i) {var entry = this.tryEntries[i];var record = entry.completion;if (entry.tryLoc === "root") {// Exception thrown outside of any try block that could handle// it, so set the completion value of the entire function to// throw the exception.return handle("end");}if (entry.tryLoc <= this.prev) {var hasCatch = hasOwn.call(entry, "catchLoc");var hasFinally = hasOwn.call(entry, "finallyLoc");if (hasCatch && hasFinally) {if (this.prev < entry.catchLoc) {return handle(entry.catchLoc, true);} else if (this.prev < entry.finallyLoc) {return handle(entry.finallyLoc);}} else if (hasCatch) {if (this.prev < entry.catchLoc) {return handle(entry.catchLoc, true);}} else if (hasFinally) {if (this.prev < entry.finallyLoc) {return handle(entry.finallyLoc);}} else {throw new Error("try statement without catch or finally");}}}},abrupt: function(type, arg) {for (var i = this.tryEntries.length - 1; i >= 0; --i) {var entry = this.tryEntries[i];if (entry.tryLoc <= this.prev &&hasOwn.call(entry, "finallyLoc") &&this.prev < entry.finallyLoc) {var finallyEntry = entry;break;}}if (finallyEntry &&(type === "break" ||type === "continue") &&finallyEntry.tryLoc <= arg &&arg <= finallyEntry.finallyLoc) {// Ignore the finally entry if control is not jumping to a// location outside the try/catch block.finallyEntry = null;}var record = finallyEntry ? finallyEntry.completion : {};record.type = type;record.arg = arg;if (finallyEntry) {this.method = "next";this.next = finallyEntry.finallyLoc;return ContinueSentinel;}return this.complete(record);},complete: function(record, afterLoc) {if (record.type === "throw") {throw record.arg;}if (record.type === "break" ||record.type === "continue") {this.next = record.arg;} else if (record.type === "return") {this.rval = this.arg = record.arg;this.method = "return";this.next = "end";} else if (record.type === "normal" && afterLoc) {this.next = afterLoc;}return ContinueSentinel;},finish: function(finallyLoc) {for (var i = this.tryEntries.length - 1; i >= 0; --i) {var entry = this.tryEntries[i];if (entry.finallyLoc === finallyLoc) {this.complete(entry.completion, entry.afterLoc);resetTryEntry(entry);return ContinueSentinel;}}},"catch": function(tryLoc) {for (var i = this.tryEntries.length - 1; i >= 0; --i) {var entry = this.tryEntries[i];if (entry.tryLoc === tryLoc) {var record = entry.completion;if (record.type === "throw") {var thrown = record.arg;resetTryEntry(entry);}return thrown;}}// The context.catch method must only be called with a location// argument that corresponds to a known catch block.throw new Error("illegal catch attempt");},delegateYield: function(iterable, resultName, nextLoc) {this.delegate = {iterator: values(iterable),resultName: resultName,nextLoc: nextLoc};if (this.method === "next") {// Deliberately forget the last sent value so that we don't// accidentally pass it on to the delegate.this.arg = undefined;}return ContinueSentinel;}};// Regardless of whether this script is executing as a CommonJS module// or not, return the runtime object so that we can declare the variable// regeneratorRuntime in the outer scope, which allows this module to be// injected easily by `bin/regenerator --include-runtime script.js`.return exports;}(// If this script is executing as a CommonJS module, use module.exports// as the regeneratorRuntime namespace. Otherwise create a new empty// object. Either way, the resulting object will be used to initialize// the regeneratorRuntime variable at the top of this file.typeof module === "object" ? module.exports : {}
));

这篇关于10简化返回数据和使用es7的async语法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/534168

相关文章

大模型研发全揭秘:客服工单数据标注的完整攻略

在人工智能(AI)领域,数据标注是模型训练过程中至关重要的一步。无论你是新手还是有经验的从业者,掌握数据标注的技术细节和常见问题的解决方案都能为你的AI项目增添不少价值。在电信运营商的客服系统中,工单数据是客户问题和解决方案的重要记录。通过对这些工单数据进行有效标注,不仅能够帮助提升客服自动化系统的智能化水平,还能优化客户服务流程,提高客户满意度。本文将详细介绍如何在电信运营商客服工单的背景下进行

基于MySQL Binlog的Elasticsearch数据同步实践

一、为什么要做 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品、订单等数据的多维度检索。 使用 Elasticsearch 存储业务数据可以很好的解决我们业务中的搜索需求。而数据进行异构存储后,随之而来的就是数据同步的问题。 二、现有方法及问题 对于数据同步,我们目前的解决方案是建立数据中间表。把需要检索的业务数据,统一放到一张M

关于数据埋点,你需要了解这些基本知识

产品汪每天都在和数据打交道,你知道数据来自哪里吗? 移动app端内的用户行为数据大多来自埋点,了解一些埋点知识,能和数据分析师、技术侃大山,参与到前期的数据采集,更重要是让最终的埋点数据能为我所用,否则可怜巴巴等上几个月是常有的事。   埋点类型 根据埋点方式,可以区分为: 手动埋点半自动埋点全自动埋点 秉承“任何事物都有两面性”的道理:自动程度高的,能解决通用统计,便于统一化管理,但个性化定

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

异构存储(冷热数据分离)

异构存储主要解决不同的数据,存储在不同类型的硬盘中,达到最佳性能的问题。 异构存储Shell操作 (1)查看当前有哪些存储策略可以用 [lytfly@hadoop102 hadoop-3.1.4]$ hdfs storagepolicies -listPolicies (2)为指定路径(数据存储目录)设置指定的存储策略 hdfs storagepolicies -setStoragePo

Hadoop集群数据均衡之磁盘间数据均衡

生产环境,由于硬盘空间不足,往往需要增加一块硬盘。刚加载的硬盘没有数据时,可以执行磁盘数据均衡命令。(Hadoop3.x新特性) plan后面带的节点的名字必须是已经存在的,并且是需要均衡的节点。 如果节点不存在,会报如下错误: 如果节点只有一个硬盘的话,不会创建均衡计划: (1)生成均衡计划 hdfs diskbalancer -plan hadoop102 (2)执行均衡计划 hd

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传