【问题标题】:javascript async/await and promisejavascript 异步/等待和承诺
【发布时间】:2019-07-26 23:04:47
【问题描述】:

我很难理解 async/await 是如何工作的。我必须制作一个包含三个函数的程序:func1func2concatenatedfunc1 将字符串作为参数并在延迟 5 秒后返回相同的字符串,func2 是一个 async 函数,它也将字符串作为参数并返回相同的字符串。 concatenated 是一个函数,它接受两个字符串 (s1,s2) 作为参数,并使用上述两个函数((func1(s1) and func2(s2)))在 5 秒后返回它们的连接结果。所以如果我们将("hello"," world") 传递给concatenated 它应该返回hello world。我的代码是:

function func1(x) {
return new Promise(resolve => {
setTimeout(() => {
  resolve(x);
    }, 5000);
  });
 }

async function func2(x) {
const a = await func1(x);
return a;
}

function concatenated(a,b){
  const c = func2(a).then(result =>{console.log(result)});
  const d = func2(b).then(result =>{console.log(result)});
  return (c+d) ;
} 

concatenated("hello"," world")

此代码只给我:
hello world

我该如何纠正这个问题?

【问题讨论】:

  • 为什么你的concatenated函数不用await,而是then?注意cd 都是promise(对于undefined,是回调的结果)。

标签: javascript promise async-await


【解决方案1】:

问题是您来自concatenated 函数的return 语句将同步 运行。这也意味着cd 仍将是承诺。

一个可能的解决方案是:

async function concatenated(a,b){
  const c = await func2(a);
  const d = await func2(b);

  return (c+d);
} 

concatenated("hello", " world").then(result => {
    console.log(result); // hello world
})

请注意,异步函数将始终返回一个承诺。

【讨论】:

    【解决方案2】:

    你可以像这样在 5 秒后得到结果:

    function func1(x) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(x);
        }, 5000);
      });
     }
    
    async function func2(x) {
      const a = await func1(x);
      return a;
    }
    
    async function concatenated(a,b){
      const [c,d] = await Promise.all([func2(a), func2(b)])
      return c+d;
    }
    
    (async function main() {
      const ret = await concatenated("hello"," world")
      console.log(ret)
    })()

    使用 JavaScript async/await 语法,您可以像同步风格一样编写异步代码。不需要promise.then,不需要回调。它与其他语言有点不同,例如去吧,Java

    【讨论】:

      【解决方案3】:

      您似乎误解了控制台日志。一个普通的console.log 总是会换行,这就是为什么你在两行而不是一行上看到 hello world。假设您使用的是 Node.js,您可以使用以下内容在没有换行符的情况下写入控制台以达​​到您想要的结果:

      process.stdout.write(result);

      【讨论】:

        猜你喜欢
        • 2021-10-07
        • 2018-10-17
        • 2017-06-15
        • 1970-01-01
        • 2018-03-02
        • 2018-09-02
        • 1970-01-01
        • 1970-01-01
        • 2018-04-17
        相关资源
        最近更新 更多