[英]javascript async/await and promise
我很難理解async / await是如何工作的。我必須創建一個包含三個函數的程序: func1
func2
和concatenated
。 func1
將一個字符串作為參數,並在延遲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
函數的return語句將同步運行。 這也意味着c
和d
仍將是承諾。
一個可能的解決方案是:
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
})
請注意, 異步函數將始終返回promise。
你可以在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
,不需要回電。 它與其他語言略有不同,例如Go,Java
你似乎誤解了控制台日志。 常規的console.log
將始終使用換行符,這就是為什么您在兩行而不是一行上看到hello world的原因。 假設您正在使用Node.js,您可以使用以下內容寫入控制台而不使用換行符來實現您期望的結果:
process.stdout.write(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.