如何将承诺转换为异步等待

我正在将带有 promise 函数的不同代码片段转换为异步等待函数。 VS Code 可以自动完成,但在某些地方我必须手动完成,因为 VS Code 没有突出显示 promise 语法。有人能告诉我一个基于这个表达式将 promise 转换为 async 的例子吗?

const getJson = url => fetch(url).then(res => res.json());

    getJson('/i/1.json')
    .then(json => {
        if (json.key) {
            return getJson('/i/2.json')
        }
        throw new Error('No key')
    })
    .then(json => {
        return json.key2
    })
    .catch(error => {
        console.error(error)
    })

关注这篇文章https://advancedweb.hu/how-to-refactor-a-promise-chain-to-async-functions/ 我想我应该得到这样的东西:

const getJson = url => fetch(url).then(res => res.json());

const getJson1 = await getJson();
const getJson2 = await getJson2(key);
const getJson3 = await getJson3(key2);

jinzhenghe 回答:如何将承诺转换为异步等待

类似的东西

const getJson = async (url) => {
  const res = await fetch(url)
  return res.json()
}

const yourFetch = async () => {
  try {
    const json = await getJson('/i/1.json')
    
    if (json.key)  {
      const json2 = await getJson('/i/2.json')
      return json2.key
    }

    throw new Error('No key')
  } catch (err) {
    console.error(err)
  }
}
,

func subscribeToResponse() { homeViewModel.filterModelObservable.bind(to: self.tableView.rx.items(cellIdentifier: HomeTableViewCell.reuseIdentifier,cellType: HomeTableViewCell.self)) { row,books,cell in cell.separatorInset = UIEdgeInsets(top: 0,left: 0,bottom: 20,right: UIScreen.main.bounds.width) cell.titleLabel.text = books.name cell.secondaryTitleLabel.text = books.type cell.selectionStyle = .none if books.available == true { cell.avalibaleOrNotLabel.text = "Avalibale" cell.avalibaleOrNotStatus.backgroundColor = .green } else { cell.avalibaleOrNotLabel.text = "Not Avalibale" cell.avalibaleOrNotStatus.backgroundColor = .gray } }.disposed(by: disposeBage) } (模块除外)仅在异步函数内有效。所以让我们创建一个 Async IIFE

await

如果您预先知道路径,您可以选择Promise.all

const url = "https://jsonplaceholder.typicode.com";
const getJson = async url => await fetch(url).then(res => res.json());

;(async () => { // Async IIFE
    
  const getJson1 = await getJson(`${url}/users/1`);
  if (!getJson1.id) throw new Error('No ID');
  const getJson2 = await getJson(`${url}/todos/${getJson1.id}`);
  console.log(getJson2);

})();

console.log("PS: I don't wait for the above to finish");

本文链接:https://www.f2er.com/1173.html

大家都在问