我以為我對 Node 和 Promises 有很好的理解,但是當我試圖為我的朋友解釋一些事情時,我遇到了這個問題。
我想問你們,這個小腳本的預期輸出是什么?
const myPromise = new Promise((resolve, reject) => {
console.log("inside promise")
resolve("Lol!")
})
setTimeout(() => {}, 100)
myPromise.then(() => console.log("then!"))
console.log("finished")
我的預期輸出:
inside promise
finished
我的想法是,如果承諾一旦定義就立即執行,那么讀取 then 應該不到 100 毫秒,從而使其過時。但我想我錯了:
實際輸出:
inside promise
finished
then!
如果我發出resolve("Lol!")雖然預期的輸出與實際輸出匹配。
有人能解釋一下這里發生了什么嗎?
謝謝!
uj5u.com熱心網友回復:
這是您注釋的示例:
console.log('Before myPromise is created');
const myPromise = new Promise((resolve, reject) => {
// This is executed immediately when a new
// Promise is created, so it will appear
// BEFORE 'After myPromise is created'.
console.log("Inside promise")
// This passes the value "Lol!" to
// the 'then' function. By itself it
// does not console log anything.
resolve("Lol!")
})
console.log('After myPromise is created');
// This does nothing, code immediately
// carries on executing. After >=100ms a function
// doing nothing is called.
setTimeout(() => {}, 100)
// The 'then' is passed the argument of
// `resolve()` (in this case "Lol!")
myPromise.then(resolveArg => console.log(resolveArg))
// Second to last console log because
// all .then() handlers are called asynchronously
// once the main thread is idle (as the Promises/A
// spec says, when the JS engine returns back to
// "platform code"). Therefore "Lol!" will be the
// last thing logged.
console.log("Finished")
uj5u.com熱心網友回復:
JS promise 為您提供異步運行代碼的選項。因此,您向 JS 引擎發出信號,表示您希望在另一個操作完成后執行一個操作。由于行動可以成功或不成功,承諾可以被解決 ( resolve) 或拒絕 ( reject)。對于處理成功您使用then的處理失敗您使用catch,可選之后您可以使用finally。
所以當你宣告一個 promise 時,JS 引擎知道它不是你現在需要的,而是以后需要的。所以它首先運行你同步給它的命令,在你的情況下,除了then. 完成后,它會檢查是否有已經解決的承諾,如果是,它將執行相關的than.
resolve()將then承諾的放入回呼佇列。稍后當呼叫堆疊為空時,引擎將處理它。同樣會去,reject()但與catch.
如果您想保持更簡潔的語法,我建議您檢查 async-await。
*另請注意,您setTimeout沒有給您任何東西。如果你把console.log它放進去,它也只會在“完成”后顯示。
uj5u.com熱心網友回復:
new Promise()處理它必須“等待”的操作,然后將結果回傳給then ()命令——這是一個異步操作。考慮以下示例:
const myPromise = (val1, val2) => {
return new Promise((resolve, reject) => {
val1 > val2
? setTimeout(() => resolve("LOL !!!"), 1500)
: reject("\"val2\" is greater than \"val1\"");
});
}
// Then you call:
myPromise(5, 1).then(
// Processing results:
function (result) {
console.log("This is result: ", result);
},
// Error handling from "reject()"
function(error) {
console.log("This is an error: ", error);
}
)
// error case:
myPromise(1, 5).then(
// Processing results:
function (result) {
console.log("This is result: ", result);
},
// Error handling from "reject()"
// the result in console.log will be first than in the case of resolve()
function(error) {
console.log("This is an error: ", error);
}
)
// Error handling with 'catch' block
myPromise(1,5)
.then((result) => console.log(result))
.catch((err) => console.log("This is error: ", err, "# with catch-block"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/339479.html
標籤:javascript 节点.js 异步
