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

Promise.race 的反面怎么写

Promise.race 的反面怎么写

四季花海 2021-11-04 15:20:14
我有一些 3 个异步函数。我必须创建函数来获取 3 个函数和参数中的一些回调,并在最后一个异步函数结束时调用该回调,然后将该函数的回调参数的值发送到回调。这 3 个函数有 1 个回调参数:const async1 = (cb) => {    setTimeout(() => {        cb(1);    }, 4000);};const async2 = (cb) => {    setTimeout(() => {        cb(13);    }, 6000);};const async3 = (cb) => {    setTimeout(() => {        cb(5);    }, 3000);};const someCallback = (val) => console.log(val); yourXFunction(async1, async2, async3, someCallback); // for this case, should print 13

1 回答

?
心有法竹

TA贡献1866条经验 获得超5个赞

您可以轻松实现这样的功能:


function yourXFunction(...args){

  const cb=args.pop()

  const cbCreator=i=>value=>{

    if(done.add(i).size===args.length){

      cb(value)

    }

  }

  const done=new Set

  args.map((fn,i)=>{

    fn(cbCreator(i))

  })

}

但请注意...


避免使用回调来支持 Promises(或者,甚至更好,async/ await)

由于 JS 的单线程性,竞相“异步”的事情可能会产生意想不到的结果

这是您的代码的承诺版本:


const wait = t => new Promise(rs => setTimeout(rs, t))

const async1 = () => wait(4000).then(()=>1)

const async2 = () => wait(6000).then(()=>13)

const async3 = () => wait(3000).then(()=>5)


function promisifiedYourXFunction(...args){

  return new Promise(resolve=>{

    const cbCreator=i=>value=>{

      if(done.add(i).size===args.length){

        resolve(value)

      }

    }

    const done=new Set

    args.map((fn,i)=>{

      fn().then(cbCreator(i))

    })

  })

}


promisifiedYourXFunction(async1, async2, async3)

.then(console.log)


查看完整回答
反对 回复 2021-11-04

添加回答

代码语言

举报

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