[英]java script promises lingo
我是新的承諾,所以為新手問題道歉。 在我的 function 中,我有以下幾行(函數的中間):
...
const retPromise = await buildImgs(file, imgArray);
retPromise.then(async function () {
console.log("completed build imgs");
...
我的假設是 promise 中的“then”在等待完成之前不會執行。 但是,唉,它就像同步代碼一樣,並且 retPromise 在 buildImgs 完成之前評估“then”(由我的 console.log 流測量)。 結果是一個未定義的 retPromise。
請幫助...我在這個概念中遺漏了什么?
好的:反饋后,讓我進一步解釋我的問題:我正在嘗試理解這個異步/同步流和控制概念:
const retVal = somefunc();
console.log(retVal);
const retVal = await somefunc();
console.log(retVal);
在第一種情況下,如果我正確理解了同步/異步代碼,那么當 console.log 找到它時,我應該有可能未定義 retVal ......
在第二種情況下,我認為它會停止流動,直到 somefunc() 完成,然后流動將繼續。 但是,我的閱讀似乎表明它仍會嘗試將 console.log 消息作為並行線程運行。 所以這讓我相信我需要將 console.log 放在 the.then 的 somefunc 之后。 這讓我做出了承諾。 所以我做了一個 promise 返回,我看到這正在發生。
但是,the.then,就像我原來的帖子代碼一樣,似乎在我的 buildImgs 中的代碼完成之前發布了控制台消息“完成構建 imgs”(通過我知道要使用的 function 以及 buildImgs 中的控制台消息來衡量的時間來衡量)幫我測序)
所以在我看來,我仍然缺少有關如何阻止異步代碼流的基礎知識。 :(
當您使用await
構造時,腳本將等待 promise 解析並從此 promise 返回您的retPromise
值。 所以在這種情況下最好選擇一個。 刪除await
並保留then
,或保留await
並使用retPromise
值。
假設buildImgs
實際上返回 promise (示例)
const buildImgs = (file, imgArray) => {
return new Promise((resolve, reject) => {
try {
// ...
resolve()
} catch (err) {
reject(err)
}
})
}
當您在 promise 上調用await
時,它已經在等待 promise 完成,如果您在調用中刪除await
那么您可以使用.then
有兩種方法可以編寫 promise 處理程序,舊的方法看起來像這樣
buildImgs(file, imgArray)
.then(() => {
console.log('im done')
})
.catch(err => {
console.error(err)
})
和較新的語法
// you must declare "async" in order to use "await"
const asyncFunction = async () => {
try {
await buildImgs(file, imgArray)
console.log('im done')
} catch(err) {
console.error(err)
}
}
asyncFunction()
如果您需要 promise 的返回值,則將其分配給變量
const ineedResponse = await buildImgs(file, imgArray)
console.log(ineedResponse)
// or
buildImgs(file, imgArray)
.then(ineedResponse => {
console.log(ineedResponse)
})
.catch(err => {
console.error(err)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.