promiseの用法例と実施原理について
30322 ワード
記事の目次.用法例 .ES 7書き方 .promiseの原理を実現する 1.用法の例
lilei('yo~~').then(hanmeimei).then(liming)
function lilei(bang){
return new Promise((open)=>{
console.log(' ')
setTimeout(() => {
console.log(' ')
console.log(bang)
open(bang)
}, 5000);
})
}
function hanmeimei(bang){
return new Promise((open)=>{
console.log(' ')
setTimeout(() => {
console.log(' ')
console.log(bang)
open(bang)
}, 5000);
})
}
function liming(bang){
return new Promise((open)=>{
console.log(' ')
setTimeout(() => {
console.log(' ')
console.log(bang)
console.log(' ')
open(bang)
}, 5000);
})
}
2.ES 7の書き方
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
<body>
<script>
// ES7
(async function(){
// .then
var bang = await lilei('yo~')
// ← open(bang) open return
bang = await hanmeimei(bang)
// ← open(bang) open return
await liming(bang)
})()
// lilei('yo~~~').then(hanmeimei).then(liming)
function lilei(bang){
return new Promise((open)=>{
console.log(' ')
setTimeout(() => {
console.log(' ')
console.log(bang)
open(bang)
}, 5000);
})
}
function hanmeimei(bang){
return new Promise((open)=>{
console.log(' ')
setTimeout(() => {
console.log(' ')
console.log(bang)
open(bang)
}, 5000);
})
}
function liming(bang){
return new Promise((open)=>{
console.log(' ')
setTimeout(() => {
console.log(' ')
console.log(bang)
console.log(' ')
open(bang)
}, 5000);
})
}
script>
body>
html>
3.promiseの原理を実現する
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
<body>
<script>
function MyPromise(task){
console.log('enter MyPromise')
var self = this //
self.status = 'pending' // , , pending, ; open,
self.data // promise
self.nextTask //
// open ,
// open , , open
function open(data){
// pending, open
if(self.status === 'pending'){
self.status = 'open'
// then , open ,
if(typeof self.nextTask === 'function'){
self.nextTask(data)
}
}
}
task(open)
}
MyPromise.prototype.then = function(nextTask){
// then , then nextTask ,
this.nextTask = nextTask
}
lilei('yo~~').then(hanmeimei)
function lilei(bang){
return new MyPromise((open)=>{
console.log(' ')
setTimeout(() => {
console.log(' ')
console.log(bang)
open(bang)
}, 5000);
})
}
function hanmeimei(bang){
return new MyPromise((open)=>{
console.log(' ')
setTimeout(() => {
console.log(' ')
console.log(bang)
open(bang)
}, 5000);
})
}
function liming(bang){
return new MyPromise((open)=>{
console.log(' ')
setTimeout(() => {
console.log(' ')
console.log(bang)
console.log(' ')
open(bang)
}, 5000);
})
}
script>
body>
html>