javascript async/await and promise [英] javascript async/await and promise
问题描述
我很难理解异步/等待的工作方式,我必须编写一个包含以下三个功能的程序: func1
func2
和 concatenated
. func1
将一个字符串作为参数,并在延迟5秒后返回相同的字符串, func2
是一个 async
函数,该函数还将一个字符串作为一个参数并返回相同的字符串. concatenated
是一个函数,它使用两个字符串(s1,s2)
作为参数,并使用上述两个函数((func1(s1)和func2(s2)))
)在5秒后返回其串联结果.因此,如果我们将("hello","world")
传递给 concatenated
,它将返回 hello world
.我的代码是:
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")
此代码仅给我:你好世界
我该如何纠正?
推荐答案
问题是您从 concatenated
函数返回的语句将同步运行.这也意味着 c
和 d
仍然是承诺.
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.
可能的解决方案是:
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.
这篇关于javascript async/await and promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!