Javascript 在这个超级代理呼叫中如何使用aysnc/WAIT?
这是一个superagent调用,我已导入请求(即从superagent组件类导出) 如何在“res.resImpVariable”中使用async/awaitJavascript 在这个超级代理呼叫中如何使用aysnc/WAIT?,javascript,reactjs,asynchronous,mobx,superagent,Javascript,Reactjs,Asynchronous,Mobx,Superagent,这是一个superagent调用,我已导入请求(即从superagent组件类导出) 如何在“res.resImpVariable”中使用async/await 我重新拟定了我的答案。我想我以前误解了。您可以将整个序列包装到一个承诺返回函数中,该函数在响应回调后解析: function callSuperagent() { return new Promise((resolve, reject) => { return request
我重新拟定了我的答案。我想我以前误解了。您可以将整个序列包装到一个承诺返回函数中,该函数在响应回调后解析:
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);
})
这适用于回调模式,因此要将其移动到async await,您需要将更改转换为返回promisesure,如何将其添加到代码中?谢谢,我在哪里添加doSomething方法?解决后立即?所有内容都包含在其中。您可以用两个函数定义(可以在该文件中的任何位置)和一个对
doSomething()
的调用来替换现有的所有内容。我很难改进我所说的内容,因为我看不到request.post().send().end()前后的内容
callSuperagent()
.then((res) => {
console.log('res', res);
console.log('and our friend:', res.resImpVariable);
})
.catch((err) => {
console.log('err', err);
})