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:
請貼出你的代碼,而不是截圖,這是提問的一個小技巧哦,圖片不怎么清晰。
