Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use JavaScript Promise

Shulou Source: shulou.com Published: 2022-06-01 03:29:46 09月22日 Update

Today, I would like to share with you the relevant knowledge of how to use JavaScript Promise. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

JavaScript Promise instance

Examples of using callbacks

SetTimeout (function () {myFunction ("I love You!!");}, 3000)

Function myFunction (value) {

Document.getElementById ("demo"). InnerHTML = value

}

Example of using Promise

Let myPromise = new Promise (function (myResolve, myReject) {

SetTimeout (function () {myResolve ("I love You!!");}, 3000)

})

MyPromise.then (function (value) {

Document.getElementById ("demo"). InnerHTML = value

})

Examples of using callbacks

Function getFile (myCallback) {

Let req = new XMLHttpRequest ()

Req.open ('GET', "mycar.html")

Req.onload = function () {

If (req.status = = 200) {

MyCallback (req.responseText)

} else {

MyCallback ("Error:" + req.status)

}

}

Req.send ()

}

GetFile (myDisplayer)

Example of using Promise

Let myPromise = new Promise (function (myResolve, myReject) {

Let req = new XMLHttpRequest ()

Req.open ('GET', "mycar.htm")

Req.onload = function () {

If (req.status = = 200) {

MyResolve (req.response)

} else {

MyReject ("File not Found")

}

}

Req.send ()

})

MyPromise.then (

Function (value) {myDisplayer (value);}

Function (error) {myDisplayer (error);}

)

These are all the contents of the article "how to use JavaScript Promise". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Tags: Examples knowledge articles content different very big most examples that is more knowledge points industry information information channels logic facets channels Tiandu reference learning Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux vpn OPPO Reno Shulou Information Huawei