如何使用承诺和使用结果以后与我的代码?



我是异步操作和js的新手。这是我的问题。我有一个Person类。我想用我从API调用中获得的数据初始化Person实例。

class Person { 
constructor(data) {
this.data = data;
}
}

我正在使用Axios进行API调用。我得到一个响应,并想在我的类中使用它。

const res = axios.get('https://findperson.com/api/david');
const david = new Person(res);

我明白res在这个阶段是一个承诺,我需要消耗它。我该怎么做呢?我该如何接受回应并正确使用它?

axios.get()返回一个对象的承诺,其中包含返回的数据,状态,标头等…

async function getPerson() {
try {
const res = await axios.get('https://findperson.com/api/david');
const david = new Person(res.data);
// do something with david
} catch (error) {
console.log(error)
}
}

function getPerson() {
axios
.get('https://findperson.com/api/david')
.then(res => {
const david = new Person(res.data)
// do something with david
})
.catch(console.log)
}

在另一个async函数中,或在模块的顶层或在REPL中(在节点16.6+或启用了--experimental-repl-await功能的更早版本中),您可以使用await

const res = await axios.get('https://findperson.com/api/david');

将等待promise被解析并将其解包装以将包含的值存储在res中。

如果你想把这个值从异步的世界里移到同步的世界里,你必须通过一个回调函数对它做一些事情:

axios.get('https://findperson.com/api/david').then(
res => { 
// do stuff with res here
});

…但是不要被愚弄了;如果没有await,在axios.get调用之后的任何代码都将立即运行,而无需等待回调。所以你不能在回调中复制res到全局变量然后期望它在后续代码中被设置;它必须一直是回调

你可以这样做:

axios.get('https://findperson.com/api/david').then(res => {
const david = new Person(res);
});

或者在async函数中:(参见async await for javascript)

const res = await axios.get('https://findperson.com/api/david');
const david = new Person(res);

最新更新