本文主要和大家分享ajax和promise的結合使用方法,在需要依賴完成的ajax請求可使用promise保證執行順序 在第一個請求正確返回後再發送第二個請求。希望能幫助大家。
/* 定义一个使用promise的ajax请求,这里依赖jquery 参数中请求url为必填参数 */ const ajaxPromise= param => { return new Promise((resovle, reject) => { $.ajax({ "type":param.type || "get", "async":param.async || true, "url":param.url, "data":param.data || "", "success": res => { resovle(res); }, "error": err => { reject(err); } }) }) } /* 第一个请求 */ let step1 = () => { ajaxPromise({ "url":"", }).then(res => { console.log("第一个请求正确返回==>"+res); step2(res); }).catch(err => { console.log("第一个请求失败"); }) } /* 第二个请求 */ let step2 = (res) => { ajaxPromise({ "type":"get", "url":"", "data":{"name":res} }).then(res => { console.log("第二个请求正确返回==>"+res); }).catch(err => { console.log("第二个请求失败==>"+err); }) } step1();
原生js寫入ajaxpromise物件
const ajaxPromise = param => { return new Promise((resovle, reject) => { var xhr = new XMLHttpRequest(); xhr.open(param.type || "get", param.url, true); xhr.send(param.data || null); xhr.onreadystatechange = () => { var DONE = 4; // readyState 4 代表已向服务器发送请求 var OK = 200; // status 200 代表服务器返回成功 if(xhr.readyState === DONE){ if(xhr.status === OK){ resovle(JSON.parse(xhr.responseText)); } else{ reject(JSON.parse(xhr.responseText)); } } } }) }
關於promise使用時的幾點:
使用方法:先建立一個promise物件new Promise(),根據業務需求判斷執行成功或失敗,成功呼叫resovle(),失敗則呼叫reject()。
-
Promise物件的then(onFulfilled,onRejected)有兩個參數,成功執行onFulfilled,失敗執行onRejectd
p.then(function(value) { // fulfillment成功 }, function(reason) { // rejection失败 }); //不过通常会使用catch()来捕获失败,上段代码通常写为: p.then(function(value) { // fulfillment成功 }).catch(function(reason) { //rejection失败 })
Promise物件的then ()會傳回一個新的Promise物件
相關推薦:
以上是ajax和promise的結合使用方法分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

tomakephpapplicationsfaster,關注台詞:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

到ImprovephPapplicationspeed,關注台詞:1)啟用opcodeCachingwithapCutoredUcescriptexecutiontime.2)實現databasequerycachingingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandreduceconnection.4 limitesclection.4.4

依赖注入(DI)通过显式传递依赖关系,显著提升了PHP代码的可测试性。1)DI解耦类与具体实现,使测试和维护更灵活。2)三种类型中,构造函数注入明确表达依赖,保持状态一致。3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

phpisusedforsenderemailsduetoitsbuilt-inmail()函數andsupportivelibrariesLikePhpMailerAndSwiftMailer.1)usethemail()functionForbasiceMails,butithasimails.2)butithasimail.2)

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显著提升PHP应用的性能。

依賴性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增強量強制性,可驗證性和MATIALWINABIOS.ItallowSpasspassingDepentenciesLikEdenciesLikedAbaseConnectionStoclasseconnectionStoclasseSasasasasareTers,interitationAseTestingEaseTestingEaseTestingEaseTestingEasingAndScalability。

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

WebStorm Mac版
好用的JavaScript開發工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具