为了账号安全,请及时绑定邮箱和手机立即绑定

如何添加 2 个开放功能但延迟一个?

如何添加 2 个开放功能但延迟一个?

HUH函数 2021-06-11 15:02:22
我需要制作一个应用程序,它使用功能工具来戳狗,然后延迟它来戳一个老人。你能帮助我使用功能工具来冲压 2 个物体吗(不是同时)?谢谢你。我试过用...function open2() {  // code here}而且我也尝试使用...function open() {  // code here}对于他们俩function open(){  stamp ('dog14',600,850,200)  sound ('dog')  sound('old man')  stamp('old man',300,700)}当我使用该代码时,狗和老人同时被盖章,但我需要在狗之后 3 秒盖章老人。
查看完整描述

2 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

您可以定义一个函数并包含超时。包含Promises是管理异步操作的更简单的替代方法。下面是四个函数:

  1. 邮票(图)

  2. 声音(图)

  3. 邮票和声音(图)

    • 如果figure为空或未定义,则承诺会被拒绝。该catch方法捕获并记录返回的内容。在这种情况下,'Nothing to stamp and sound'返回。

    • 否则stampsound被调用,并承诺做出决议

    • 返回一个异步操作

  4. 打开()

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();


查看完整回答
反对 回复 2021-06-24
  • 2 回答
  • 0 关注
  • 152 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信