这是一个 super 代理调用,我已经导入了请求(即从我的 super 代理组件类中导出) 我如何在“res.resImpVariable”中使用 async/await。
request
.post(my api call)
.send(params) // an object of parameters that is to be sent to api
.end((err, res) => {
if(!err) {
let impVariable = res.resImpVariable;
} else {
console.log('error present');
}
});
最佳答案
我重新表述了我的答案。我想我之前误解了。您可以将整个序列包装到一个 Promise 返回函数中,该函数在响应回调之后解析:
function callSuperagent() {
return new Promise((resolve, reject) => {
return request
.post(my api call)
.send(params) // an object of parameters that is to be sent to api
.end((err, res) => {
if(!err) {
console.log('get response', res);
// uncomment this to see the catch block work
// reject('Bonus error.');
resolve(res);
} else {
console.log('error present', err);
reject(err);
}
});
});
}
然后,您可以创建一个异步函数并等待它:
async function doSomething() {
try {
const res = await callSuperagent();
// uncomment this to see the catch block work
// throw 'Artificial error.';
console.log('res', res);
console.log('and our friend:', res.resImpVariable);
} catch (error) {
throw new Error(`Problem doing something: ${error}.`);
}
}
doSomething();
或者如果你不做doSomething
,它会是这样的:
callSuperagent()
.then((res) => {
console.log('res', res);
console.log('and our friend:', res.resImpVariable);
})
.catch((err) => {
console.log('err', err);
})
关于javascript - 如何在此 super 代理调用中使用 async/await?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62187645/