How to use JavaScript Promise
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.