【问题标题】:Is there a way to make async function sync?有没有办法使异步功能同步?
【发布时间】:2022-01-25 14:47:42
【问题描述】:

我有这样的代码。

async function doAsync(count){
  //external function I need to use
  count++;
  console.log("async count is "+ count );
  return await count;
}
 
function makeSyncChain(i){
  //my chain that I could change
  i=doAsync(i);
  return i;
}

let val=0;
console.log("sync count is " + makeSyncChain(val));
所以就像在这个例子中,我有同步链,其中一个链函数是异步的,有没有办法让异步函数在同步链中工作?

【问题讨论】:

  • 不使用await是同步的。在您的情况下,“异步”前缀是完全多余的。
  • 没有。使用异步几乎总是意味着需要等待将来的某些东西到达。我说 “几乎总是” 因为你的例子没有。您实际上所做的任何事情都不需要使用异步
  • 一个异步函数返回一个承诺,因此您需要处理该承诺解析以访问您想要的内容
  • 感谢您的回答,但异步函数不是我的函数,我无法更改它,作为一种选择,我正在尝试使用带有承诺的异步链,但是当我需要值时它会返回我的承诺( (

标签: javascript


【解决方案1】:

正确的解决方案必须是:

async function doAsync(count){
  //external function I need to use
  count++;
  console.log("async count is "+ count );
  return await count;
}

let val=0;
console.log("sync count is " + (await doAsync(val)));

但错误的键可能会写成(是的它不起作用,它只会挂起浏览器):

async function doAsync(count){
  //external function I need to use
  count++;
  console.log("async count is "+ count );
  return await count;
}
 
function makeSyncChain(i){
  //my chain that I could change
  let isDone = false;
  let result;
  doAsync(i).then(r => {
    result = r;
  }).finally(() => {
    isDone = true;
  });
  while (!isDone);
  return result;
}

let val=0;
console.log("sync count is " + makeSyncChain(val));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-06
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    相关资源
    最近更新 更多