[英]Promise { pending }, async, await in Javascript
我試圖理解為什么這段代碼會返回“Promise { pending }”。
const reduceDirections = (str) => {
str = str.replace(/northsouth|southnorth|eastwest|westeast/ig, '')
if (str.search(/northsouth|southnorth|eastwest|westeast/ig) === -1) {
str = str.replace(/south|north|west|east/gi, '$& ').replace(/(^\s+|\s+$)/,'')
console.log(str)
return str
} else {
reduceDirections(str)
}
}
async function start(arr) {
str = arr.join('')
let res = await reduceDirections(str)
return Promise.resolve(res)
}
console.log(start(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]))
當我從 reduceDirections() function console.log(str)
可以看到我得到了我想要的結果。 但是當我(一行后) return str
時,我改為“Promise pending”
很抱歉不理解 Promises 和 async await。 我曾嘗試在 mdn 上閱讀並觀看視頻,但我不知道如何將它們顯示的內容轉移到這個問題上。 提前感謝您的幫助!
幾個問題:
1) reduceDirections
中沒有異步發生,也沒有返回 promise,因此在其上使用await
沒有任何意義。
2)你的 function 的遞歸部分不返回遞歸結果,所以改變:
} else {
reduceDirections(str)
}
至:
} else {
return reduceDirections(str)
}
那么至少你可以希望有一個有用的字符串作為返回值
3)如果你真的堅持對同步返回的東西使用await
,那么你可以保留它,但沒必要這樣做
return Promise.resolve(res)
...因為async
function 總是返回 promise 無論如何。 所以就這樣做
return res;
4)您不要等待promise解決。 所以你應該等待它的解析值並使用console.log
。 改變:
console.log(start(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]))
至:
start(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]).then(console.log)
但同樣,在這里使用 Promise 是沒有用的,只會使代碼復雜化。 你不會從中得到任何好處。
代碼返回“Promise { pending }”,因為您沒有等待 promise 完成,
應該是console.log(await start(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]))
補充:正如@trincot 提到的,您不需要使啟動異步,也不需要等待reduceDirections()。 但正如我所說, start() 的返回是一個未決的 promise 因為你沒有等待它完成。
正如@Andreas 評論的那樣,我的解決方案只能在其他異步 function 中工作,否則 start() 應該被視為 Promise start().then()
,就像@trincot 在他的回答中所做的那樣。
擺脫線return Promise.resolve(res)
。 無論如何,異步函數都會返回 promise。
您在控制台 (WEST) 上看到的第一行來自 reduceDirections function 中的 console.log 語句。
Promise{pending} 是第二個 console.log 顯示的內容,因為這是從 function 開始的返回值。
關於為什么 Promise 懸而未決的問題實際上稍微有趣一些。 It's because the function is async if you remove the async part you get a resolved promise, but using async magically wraps the returned value of the function in a promise, it's that promise which is pending and not the one created by calling Promise.resolve( )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.