Skip to content

Instantly share code, notes, and snippets.

let str = 'init'
const func = () => {
str='changed'
}
setTimeout(func,3000)
console.log(str) // ''
let data = {}
//使用 async 將 ajax 請求改為同步。
$.ajax({
url: '',
async: false,
success: (status)=>{
data = status
}
)}
const newPromise = new Promise((resolve, reject)=>{
/**成功時回傳**/
resolve(status)
/**失敗時回傳**/
reject(status)
}).then((data)=>{
/**以 then 接續成功時的處理**/
}).catch((error)=>{
/**以 catch 接續失敗時的處理**/
const newPromise = new Promise((resolve, reject)=>{
setTimeout(()=>{resolve('changed')}, 3000)
}).then((data)=>{
console.log(data) //3 秒後執行,並印出'changed'
})
const newPromise = new Promise((resolve, reject)=>{
setTimeout(()=>{
if(Math.random() > 0.5){
resolve('changed')
}
else{
reject('error')
}
}, 3000)
}).then((data)=>{
const newPromise = new Promise((resolve, reject)=>{
setTimeout(()=>{resolve('changed')}, 3000)
}).then((data)=>{
console.log(data) // 'changed'
return 'last changed'
}).then((data)=>{
console.log(data) // 'last changed'
})
const newPromise = new Promise((resolve, reject)=>{
setTimeout(()=>{resolve('changed')}, 3000)
}).then((data)=>{
console.log(data)
setTimeout(()=>{data = 'last changed'},2000)
return data
}).then((data)=>{
console.log(data) // 'changed'
})
const lastPromise = new Promise((resolve, reject)=>{
setTimeout(()=>{resolve('last changed')},2000)
})
const newPromise = new Promise((resolve, reject)=>{
setTimeout(()=>{resolve('changed')}, 3000)
}).then((data)=>{
console.log(data)
return lastPromise.then((lastData)=>{return lastData})
}).then((data)=>{
console.log(data) // 'last changed'
const newPromise = new Promise((resolve, reject)=>{
setTimeout(()=>{resolve('changed')}, 3000)
}).then((data)=>{
console.log(data)
//第二個Promise
return new Promise((resolve, reject)=>{
setTimeout(()=>{resolve('last ' + data)},2000)
}).then((lastData)=>{
return lastData
})
const initState = {
name: 'Jack',
}