2 回答

TA贡献1936条经验 获得超6个赞
您可以定义一个函数并包含超时。包含Promises是管理异步操作的更简单的替代方法。下面是四个函数:
邮票(图)
声音(图)
邮票和声音(图)
如果
figure
为空或未定义,则承诺会被拒绝。该catch
方法捕获并记录返回的内容。在这种情况下,'Nothing to stamp and sound'
返回。否则,
stamp
和sound
被调用,并承诺做出决议返回一个异步操作。
打开()
function stamp(figure){
console.log(figure + ' stamped');
}
function sound(figure){
console.log(figure + ' sounded');
}
function stampAndSound(figure) {
return new Promise(function(resolve, reject) {
// if empty argument is given, reject promise
if(figure === undefined || figure == ''){
reject('Nothing to stamp and sound');
}else{
// otherwise stamp and sound
stamp(figure);
sound(figure);
resolve();
}
})
}
// define variables ...
let oldMan = 'old man';
//let dog = ''; // uncomment this line and comment the one below to test how the promise rejects
let dog = 'pitbull';
function open(){
// stampAndSound oldMan first then dog
stampAndSound(oldMan).then(function() {
// wait three seconds then stamp and sound dog
setTimeout(function(){
stampAndSound(dog).catch(function(error){ // if promise gets rejected..
console.log('Error: ' + error);
});
}, 3000)
}).catch(function(error){ // if promise gets rejected..
console.log('Error: ' + error);
})
}
open();
ES6 语法
const stamp = (figure) => { console.log(`${figure} stamped`); }
const sound = (figure) => { console.log(`${figure} sounded`); }
const stampAndSound = (figure) => {
return new Promise((resolve, reject) => {
if(figure === undefined || figure == ''){
reject('Nothing to stamp and sound');
}else{
stamp(figure);
sound(figure);
resolve();
}
})
}
// define variables ...
let oldMan = 'old man';
let dog = 'pitbull';
const open = () => {
stampAndSound(oldMan).then(() => {
setTimeout(() => {
stampAndSound(dog).catch((error) => {
console.log('Error: ' + error);
});
}, 3000);
}).catch((error) => {
console.log('Error: ' + error);
})
}
open();
添加回答
举报