【问题标题】:Returning result from asynchronous function using callbacks使用回调从异步函数返回结果
【发布时间】:2022-12-22 03:17:37
【问题描述】:

我必须编写一个函数 getABC() 的主体,它本质上必须接受来自 3 个不同函数的响应,getA()(同步)、getB(回调)(回调驱动)、getC()(基于承诺)。最终我必须返回一个聚合每个函数结果的承诺,比如 [(getA 的结果),(getB 的结果),(getC 的结果)]。

我在下面粘贴代码的 sn-p:

const [A,B,C] = ['A','B','C'];
function getA(){
 return A;
}
function getB(cb){
  setTimeout(()=>{
      cb(B);
  },10);
}
function getC()
{
   return Promise.resolve().then(()=>C)
}
function getABC()
{//Can only write the body of this function
var ARR=[];
const cb = async x =>{
const arr = [];
arr.push(getA());
arr.push(x);
arr.push(await getC());
console.log(arr); //Shows ['A','B','C'] required output
return arr;
}
let res = getB(cb);
console.log(res); //Shows undefined
return Promise.resolve().then(()=>ARR);
}
let arr = getABC().then((arr)=> console.log('Arr:',arr)); //Shows empty array ARR

` 我无法编辑代码的任何其他部分,包括 getABC() 函数调用。我无法解决这个问题。任何帮助将非常感激。提前致谢!

【问题讨论】:

    标签: javascript promise callback asynchronous-javascript


    【解决方案1】:

    像这样:

    const[A,B,C]=["A","B","C"];function getA(){return A}function getB(t){setTimeout(()=>{t(B)},10)}function getC(){return Promise.resolve().then(()=>C)}
    
    function getABC() {
      return new Promise(async(resolve) => {
        const a = getA()
        const c = await getC()
        getB((b) => resolve([a, b, c]))
      })
    }
    
    getABC().then(res => console.log(res))

    getA 的结果立即返回。 getC 返回一个承诺,所以只是 await 它的结果。然后调用getB并解决回调中的承诺。

    【讨论】:

      猜你喜欢
      • 2020-03-15
      • 2019-09-30
      • 1970-01-01
      • 2017-04-07
      • 2023-04-01
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多