如果你想串行的运行一系列的异步任务,可以按照下面的模板来处理:
const promiseChain = task1()
.then(function(task1Result) {
return task2()
})
.then(function(task2Result) {
return task3()
})
.then(function(task3Result) {
return task4()
})
.then(function(task4Result) {
console.log('done', task4Result)
})
.catch(function(err) {
console.log('Error', err)
})
这个promise链从第一个异步任务开始,每一个异步任务都返回一个promise对象,因此,我们可以使用then
方法进行链式调用。让我们来举一个例子来看看如何运用上面的模板。
假设我们有一个文本文件,它包含一些无效字符,我们要去掉这些字符。为了完成这个任务,首先,我们要读取这个文件的内容;然后,我们再移除无效字符;最后,我们把它写入到另外一个文件中。假定我们完成每一步操作的函数都返回一个promise对象,那么我们可以如下定义promise链:
code/promise/promise-in-sequence.js
const promiseChain = readFile('example.txt')
.then(function(content) {
return removeInvalidChracters(content)
})
.then(function(cleanContent) {
return writeToFile('./clean-file.txt', cleanContent)
})
.then(function() {
console.log('done')
})
.catch(function(error) {
console.log(error)
})
通过上面的promise链,使得每一个任务完成之后才会继续执行下一个任务,这样就可以让一系列任务按照既定的顺序执行。