簡體   English   中英

如何使用 async/await 將此回調轉換為承諾?

[英]How to turn this callback into a promise using async/await?

以下函數從 url 獲取圖像,加載它,並返回其寬度和高度:

function getImageData (url) {
  const img = new Image()
  img.addEventListener('load', function () {
    return { width: this.naturalWidth, height: this.naturalHeight }
  })
  img.src = url
}

問題是,如果我這樣做:

ready () {
  console.log(getImageData(this.url))
}

我得到undefined因為函數運行但圖像尚未加載。

僅當照片已加載且寬度和高度已可用時,如何使用 await/async 返回值?

如何使用async / await將這個回調函數變成一個 promise?

你沒有。 像往常一樣,您使用new Promise構造函數 沒有語法糖。

function loadImage(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.addEventListener('load', () => resolve(img));
    img.addEventListener('error', reject); // don't forget this one
    img.src = url;
  });
}

僅當照片已加載且寬度和高度已經可用時,如何使用await / async來記錄值?

你可以做

async function getImageData(url) {
  const img = await loadImage(url);
  return { width: img.naturalWidth, height: img.naturalHeight };
}
async function ready() {
  console.log(await getImageData(this.url))
}

這個庫工作得很好 - 它允許連接到子進程,或者如果需要,只需異步返回結果: https : //github.com/expo/spawn-async

暫無
暫無

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

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