javascript - Promise 封装ajax想顺序执行ajax,但是发现并没有按照顺序执行,高手指点
问题描述
代码如下:
function $myAjax(url, method, data, callback) {let p = new Promise(function(resolve, reject) { $Ajax.request({url: url,method: method,data: data,success: function(resp) { callback(resp); resolve();},failure: function(xhr) { //todo reject();} });});return p; } let $docs = document; $docs.getElementById(’xxx’).onclick = function() {$myAjax(’https://mhd.uzai.com/api/CommonActive/GetPrizeGivingByUserid’, ’get’, { ’memberid’: 1920740, ’activeid’: 1 }, function(resp) { console.log(resp); console.log(1);}).then($myAjax(’https://mhd.uzai.com/api/CommonActive/GetPrizeGivingByUserid’, ’get’, { ’memberid’: 1920740, ’activeid’: 1 }, function(resp) { console.log(resp); console.log(2);})); };`
也就是说有时候会先打印出来2,后打印出来1;
想要执行的顺序是:1,2
请高手指点!
问题解答
回答1:额, 你这个写错了,正确写法如下
$docs.getElementById(’xxx’).onclick = function() { $myAjax(’https://mhd.uzai.com/api/CommonActive/GetPrizeGivingByUserid’, ’get’, { ’memberid’: 1920740, ’activeid’: 1 }, function(resp) {console.log(resp);console.log(1); }).then(function() {$myAjax(’https://mhd.uzai.com/api/CommonActive/GetPrizeGivingByUserid’, ’get’, { ’memberid’: 1920740, ’activeid’: 1 }, function(resp) { console.log(resp); console.log(2);}) });};`回答2:
$docs.getElementById(’xxx’).onclick = async function() {let resp1 = await $myAjax(’https://mhd.uzai.com/api/CommonActive/GetPrizeGivingByUserid’)let resp2 = await $myAjax(’https://mhd.uzai.com/api/CommonActive/GetPrizeGivingByUserid’)}回答3:
你这写法,就是说没有调用reject函数,在成功触发后,你的resp输出的是什么?
回答4:你需要用数组来保证队列,用reduce来保证返回值的叠加操作。然后自己实现promise
回答5:推荐用终极方案 async。
回答6:首先,你要理解一点,Promise不需要传callback,Promise就是为了不传callback回调的。先看下Promise语法吧。
var promise=new Promise(function(resolve,reject){ //这里面执行异步操作, //参数说明:resolve,reject都是function,异步成功了,执行resolve,失败了执行reject //此处使用setTimeout模拟一个ajax setTimeout(function () {resolve(testData); }, 1000);})promise.then(function success(){//执行resolve就等于初始执行这个函数},function error(){//执行reject就等于初始执行这个函数});//多个then//promise.then....
建议看看阮一峰写的教程:Promise
回答7:所有 promise 中的then 都是按顺序调度立即执行,这些 then 中任意一个都无法影响或延误对其他的调用。也就是你的第二个 ajax 是不会等第一个 ajax 请求晚再执行。 解决办法
//ajax 的promise 封装var ajax1 = new Promise((resolve,reject) => {// request})var ajax2 = new Promise((resolve,reject) => {// request})//调用ajax1() .then(() => return ajax2()) ....回答8:
请贴出你的代码,而不是截图,这是提问的一个小技巧哦,图片不怎么清晰。
