簡體   English   中英

JS - 等待 function 內的 promise 在執行 function 之后的代碼之前完成 - 可能嗎?

[英]JS - Waiting for promise within function to finish before executing code after function -- possible?

我希望我的標題和簡單的代碼能夠解釋我想要做什么。 我正在嘗試調用 myFunction(),然后讓這些承諾通過 Promise.all 解決...然后,然后在 myfunction() 之后執行代碼;

myfunction() {
  let x = promiseOneFunction();
  let y =  promiseTwoFunction();


 Promise.all([x, y]).then(values => {
            let valOne = = values[0];
            let valTwo = values[1];

            returnObj = {
                fistVal: valOne,
                destination: valTwo
            }

            console.log("return object within promise is ", returnObj);

            return returnObj;
        });

} // end myfunction

myfunction();
console.log("want to have this log after my function is finished");

謝謝!

在 promise 完成時運行代碼的唯一(明智)方法是:

  • 在 promise 上調用then()
  • await promise

這意味着您需要myfunction在 myfunction 之外可用。 目前 function 什么都不返回。 更改它,使其返回Promise.all([x, y]).then(...)返回的 promise(您目前忽略)。

return Promise.all([x, y]).then(...)

然后 promise 將在 function 之外可用:

const the_promise = myfunction();

then你可以打電話給它。

the_promise.then(() => {
    console.log("want to have this log after my function is finished");
});

由於JS是單線程的,所有的異步函數都會被放入事件隊列,在主線程處理完當前函數/代碼塊后運行。

如果你想在 async function 之后嚴格地發生某些事情,你需要將它放在鏈接到 async function 的 a.then() 塊中,或者你可以使用新的 async/await 語法。 一樣的。

用.then()

myAsyncFunc().then(result => {
 console.log(result)
})

使用異步/等待,您首先將 function 聲明為異步 function

const myAsyncFunc = async () => {
 //Content of your function such as Promise.all
 //Returns a Promise
}

然后你這樣稱呼它:

const result = await myAsyncFunc();
console.log(result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM