[英]How make promise execute synchronously?
我使用 dom-to-image.js 將 dom 轉換為 png 圖像。 由於 dom-to-image.js 使用 promise,所以代碼是異步執行的。 我想同步執行.then function。
我有以下代碼:
domtoimage.toPng(document.getElementById("main")).then(function(dataUrl) {
console.log(dataUrl);
}).catch(function(error) {
console.error('oops, something went wrong!', error);
});
console.log("this console should be executed after console.log(dataUrl)")
我想先執行 function,然后再執行console.log("this console should be executed after console.log(dataUrl)")
。
請告訴我一些實現這一目標的方法。
對於那些現在磕磕絆絆的人:
如果您不關心IE支持,可以使用async和await來執行promise,就好像它是同步的一樣。 await
語法將暫停函數的執行,直到promise解析為止,讓您編寫代碼,好像沒有promise。 要捕獲錯誤,請將其包裝在try/catch
塊中。
唯一的問題是使用await
語法要求您將其包裝在使用async
聲明的函數中。
async function toPng() {
try {
let dataUrl = await domtoimage.toPng(document.getElementById("main"));
console.log(dataUrl);
}
catch (error ) {
console.error('oops, something went wrong!', error);
}
console.log("this console should be executed after console.log(dataUrl)")
}
當然也有合法的理由來強制JS承諾的同步執行。 最明顯的是當require
使用某些異步內容初始化的文件時,優化不是最重要的考慮因素。
看起來像包同步承諾似乎它應該做的伎倆。 在您的情況下(警告 - 未經測試..):
const dti = () => docstoimage.toPng(document.getElementById("main")) .then(dataUrl => console.log('url: ', dataUrl)) .catch(err => console.error('oops: ', err)) const sp = require('synchronized-promise') const syncDti = sp(dti) syncDti() // performs the 'synchronized version' console.log("this console should be executed afterwards")
嘗試這個:
async function doStuff(arg) {console.log(arg + "Assume this is a useful async function")}
doStuff.apply(/* What to specify as this */ this, /* List of args */ ["hello world "])
您沒有提到它是在瀏覽器中還是在 NodeJs 中完成的。 對於 NodeJs,可以使用child_process
的execSync
或spawnSync
:
import { spawnSync } from "child_process";
function doSyncStuff(domObj){
const output = spawnSync(...);
console.log("this logs in server");
return output;
異步函數是 promise。您必須對它們使用 promise 語法,或者在另一個異步 function 中對它們使用await
(異步等待語法)。常規 promise 語法的示例是: myPromise.then(() => {})
對於您正在尋找的內容,您可以對它們使用 promise 語法來等待它們,就好像它們不是 promise 一樣。不過要小心,因為myPromise.then(() => {})
中的代碼是同步的,不能使用異步等待功能。 我已經把東西包裝在一個主要的 function 中,但你不需要額外的代碼,但你不需要。 然后可以通過promise方法運行main function。 例如:
async function myFunction() {
// Do stuff
}
async function main() {
// Do stuff
await myFunction()
}
async function mySecondaryFunction() {
// Do stuff
}
function mySynchronousFunction() {
console.log("hello")
}
main().then(() => {
mySynchronousFunction()
mySecondaryFunction().then(() => {
console.log("idk")
}
})
看,我們可以使用這兩種類型的功能,知道嗎。 盡管這實際上並沒有使承諾同步。 它就像它們是同步的一樣。
編輯:呃,我剛剛意識到你可以把你想要執行的console.log
放在try
和catch
函數中。
有點死機,但我是https://www.npmjs.com/package/synchronous-promise的作者 - 在提出這個問題之前它已經存在並且做你想做的事(:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.