猿问

js延迟写入

在做一个数据处理的问题,中间会有ajax请求,最后请求到的数据不能拼接到数组中,这样改怎么处理?或者有更好的方式解决这个问题?

下面是两个方法:

牛魔王的故事
浏览 521回答 2
2回答

慕的地10843

报告楼上,这个不归axios管这个归 promise 管,要想代码好看,条件允许的情况下,使用 async 和await还有楼主,代码随便改的,不一定完全正确,但就是这么个意思function parseHtml(url, fun) {&nbsp; &nbsp; return new Promise((resolve,reject)=>{&nbsp; &nbsp; $.get(url, function(response, state, xhr) {&nbsp; &nbsp; &nbsp; &nbsp; if (state === "success" && xhr.status === 200) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let html = response.substring(response.indexOf("<body"), response.indexOf("</body>") + 7);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; html = html.trim().replace(/^\<body*?>/, "").replace(/\<\/body\>$/, "");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve(html);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reject('some error')&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; }}async function eCollapseSourceComputed() {let source = this.eCollapseSource, //&nbsp; 这是一个对象&nbsp; &nbsp; arr = [];const self = this,&nbsp; &nbsp; // 需要请求的字段&nbsp; &nbsp; needQuest = ["attachUrl", "content"];source.map(function(val) {&nbsp; &nbsp; let obj = {};&nbsp; &nbsp; needQuest.map(function(field) {&nbsp; &nbsp; &nbsp; &nbsp; let url = val[field];&nbsp; &nbsp; &nbsp; &nbsp; if (url && typeof url === "string") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 问题出在这儿&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let val= await parseHtml(url);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; arr.push(Object.assign(val, obj));});// 返回的数据没有请求到的数据return arr;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答