JavaScript promise基础示例
const { info } = console
// cooking
function cook() {
info('[COOKING] start cooking.')
const p = new Promise((resolve, reject) => {
setTimeout(() => {
info('[COOKING] complete cooking.')
resolve('[RESOLVE from cook]: rice with egg.')
}, 1000);
})
return p
}
function eat(food) {
info('[EATING] start eating.' + food)
const p = new Promise((resolve, reject) => {
setTimeout(() => {
info(`[EATING] complete eating`)
resolve('[RESOLVE from eat]: you should washing bowls and chopsticks.')
}, 1000);
})
return p
}
// cook 方法中返回了一个 Promise,使用then查看返回结果
const promise_cook = cook()
// 将cook返回的结果作为参数传递给eat
const promise_eat = promise_cook.then(food => eat(food))
// eat 方法中返回了一个 Promise,使用then查看返回结果
promise_eat.then(res => {
return new Promise((resolve, reject) => {
resolve(`[Washing] ${res} done`)
})
}).then((msg) => {
console.info(msg)
})
Keep learning