无论如何,在同一函数中,是否可以在其他人之前运行特定的 await aciton?


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'});
}
}

我有这个等待ipfs添加文件首先运行,然后第二个等待获取第一个等待的结果,然后继续。 如果第一个等待尚未完成,我希望第二个等待等待 谢谢

为了让await产生任何有意义的效果,你需要等待承诺。如果您等待非承诺,它不会抛出任何异常,但它也不会延迟继续下一个代码。

若要获取使用回调编写的代码并将其转换为承诺,需要将其包装在新的承诺中。对于您的情况,这可能如下所示:

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});

最新更新