Requirement: make a method to take data every 10 seconds; When the data is less than or equal to 4, call reject, the callback for promise failure, and print the return result; When the data is greater than 4 and less than 11, call resolve, the promise success callback function, and output the return result. At the same time, determine that when the data is greater than 10, stop and clear the timer.
The code is as follows:
Data () {return {timer: null,// timer num: 1,// default starting count}} Created () {this.promisetest (this.num)}, methods: PromiseTest (num) {new Promise(resolve, reject) => {this.timer = setTimeout(() => {/** * * Resolve indicates a successful callback, which is passed as arguments to the successful then function. * REJECT indicates a failed callback. */ if (num > 4) {resolve(' num + '); resolve(' num + '); '+ num'} else {reject(' num '+' reject ') Num ++ if (this.num > 10) {console.log(' stop and clear timer! ') clearTimeout(this.timer) } else { this.promiseTest(this.num) } }, (err) => { console.log(err) this.num++ this.promiseTest(this.num) }) }, }Copy the code
The output result is shown as follows: