如何正确解决 catch 块内的链式承诺

How to properly resolve in a chained promise inside a catch block

我正在使用 API 在服务器上创建一些资产。在创建 Promise 之后,我必须在资产上调用 process(),这是另一个 Promise API 调用。

我想编写一个将所有内容包装在一起的方法和 returns 该资产的 ID,即使 process 部分失败也应该只记录错误。

我不知道如何更改承诺,因为 catch 块只包含错误,我无法解决这个问题。

这是我目前的代码;

const apicalls = async ():Promise<string> =>{

    return new Promise((resolve)=>{
        client.getEnviornment().then(environment=>{
            environment.createAsset({/* some data */}).then((asset)=>{
                resolve(asset.id); // this id I need
                return asset; // but I need also try to call process
            }).then(asset=>{
                asset.process(); // another api call which could fail
            }).catch(error=>{
                // if the error is only from process() I just want to log it.
                console.log(error);
            })
        })
    })
}

您可以使用 async/awaittry...catch...finally 重构现有函数。

Note that unless you want the function to throw in the case that there's a problem before getting the asset ID (and if that's the behavior you desire, see the second example), you must use the return type of string | undefined because it's not guaranteed to get that far.

TS Playground

async function processAssetAndGetId (): Promise<string | undefined> {
  // because any of the steps leading up to getting the asset might fail,
  // this must be the type: string | undefined
  let id: string | undefined;
  try {
    // this could fail
    const environment = await client.getEnvironment();
    // this could fail, too
    const asset = await environment.createAsset({/* some data */});
    // set id to id of asset if we get this far
    ({id} = asset);
    // process the asset
    await asset.process();
  }
  catch (exception) {
    // if an exception is thrown at any point in the above block, log it to the console
    console.error(exception);
  }
  finally {
    return id;
  }
}

const id = await processAssetAndGetId(); // string | undefined

或者,在获取资产之前不处理潜在的异常:

TS Playground

async function processAssetAndGetId (): Promise<string> {
  // this could fail
  const environment = await client.getEnvironment();
  // this could fail, too
  const asset = await environment.createAsset({/* some data */});
  try {
    // process the asset
    await asset.process();
  }
  catch (exception) {
    // if an exception is thrown at any point in the above block, log it to the console
    console.error(exception);
  }
  return asset.id;
}

const id = await processAssetAndGetId(); // string