await ipfs.files.add(this.state.file, (err,result) => {
if(err){
console.log(err);
return
}
console.log('profile hash ' + result[0].hash);
this.setState({profilePic : result[0].hash , continue : true});
});
this.setState({loading : true,visible : 'true'});
console.log('gender value is ' + this.state.gender);
const accounts = await web3.eth.getAccounts();
console.log( 'the value of profilepic is ' + this.state.profilePic);
if(this.state.profilePic == '')
{
console.log('waiting');
}else{
try{
this.setState({continue : false});
console.log('profile hash again ' + this.state.profilePic);
await Patient.methods.insertPatient(
accounts[0],
this.state.surname,this.state.givenname,
this.state.gender,this.state.age,
this.state.email,this.state.language,
this.state.nationality,this.state.phone,
this.state.medicalno,this.state.profilePic)
.send({
from : accounts[0],
});
}
catch (e) {
console.log(e);
} finally {
this.setState({loading : false,visible : 'false'});
}
}
我让这个 await ipfs add 文件先运行,然后第二个 await 获取第一个 await 的结果,然后继续。如果第一个等待尚未完成,我希望第二个等待等待谢谢
为了await
产生任何有意义的效果,您需要等待一个承诺。如果您等待非承诺,它不会抛出任何异常,但它也不会延迟移动到下一个代码。
要将使用回调编写的代码转换为 Promise,您需要将其包装在一个新的 Promise 中。对于您的情况,这可能如下所示:
await new Promise((resolve, reject) => {
ipfs.files.add(this.state.file, (err,result) => {
if(err){
reject(err);
return;
}
console.log('profile hash ' + result[0].hash);
this.setState({profilePic : result[0].hash , continue : true});
resolve(result);
});
});
现在您正在等待承诺,此异步函数的执行将暂停,直到该承诺得到解决。异步函数中稍后的代码直到那时才会运行。
如果您对 ipfs.files.add 进行了大量调用,您可能需要创建一个辅助函数来为您创建承诺。如:
function add(file) {
return new Promise((resolve, reject) => {
ipfs.files.add(file, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
}
}
// to be used as:
const result = await add(this.state.file);
console.log('profile hash ' + result[0].hash);
this.setState({profilePic : result[0].hash , continue : true});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句