当API返回一个Promise对象时,你可以使用then()
方法来处理它的结果。then()
方法接受一个回调函数,当Promise对象被解析时会执行该回调函数,并将解析后的结果作为参数传递给回调函数。
下面是一个示例,展示如何使用then()
方法处理一个返回Promise对象的API:
// 假设你调用了一个返回Promise对象的API
const apiPromise = fetch('https://api.example.com/data');
// 使用then()方法处理Promise对象
apiPromise.then(response => {
// 在这里处理返回结果
console.log(response);
}).catch(error => {
// 如果发生错误,可以在catch()方法中处理
console.error(error);
});
在上面的示例中,我们首先使用fetch()
函数调用一个API,它返回一个Promise对象。然后,我们使用then()
方法来处理该Promise对象。在回调函数中,我们可以访问到API返回的结果response
。如果发生错误,我们可以在catch()
方法中处理异常情况。
希望这个示例能够帮助你理解如何使用返回Promise对象的API。