javascript async/await and promise

 ̄綄美尐妖づ 提交于 2021-02-10 14:14:59

问题


I'm having a hard time understanding how async/await works.I have to make a program which contains three functions: func1 func2 and concatenated. func1 takes a string as an argument and returns the same string after 5 seconds of delay, func2 is an async function which also takes a string as an argument and returns the same string. concatenated is a function that takes two strings (s1,s2) as arguments and uses the above two functions((func1(s1) and func2(s2))) to return their concatenated result after 5 seconds. So if we pass ("hello"," world") to concatenated it should return hello world. My code is:

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")

This code only gives me:
hello world

How can I correct this?


回答1:


The problem is that your return statement from the concatenated function will be run synchronously. This also means that c and d will still be promises.

A possible solution would be:

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
})

Notice that an async function will always return a promise.




回答2:


You can get the result after 5 seconds like this:

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

Using JavaScript async/await syntax, you can write the asynchronous code like the synchronous style. No need promise.then, no need callback. It's a little different from other languages, e.g. Go, Java




回答3:


You seem to be misunderstanding console logs. A regular console.log will always put a newline, which is why you are seeing hello world on two lines rather than one. Assuming you are using Node.js, you can use the following to write to the console without a newline to achieve your desired outcome:

process.stdout.write(result);



来源:https://stackoverflow.com/questions/57222364/javascript-async-await-and-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!