我有两个等待函数的变量。我只是想在完成操作后尝试控制台记录它们,但是由于跳过它们,我对它们两个都没有定义。
首先在等待功能之后发生的控制台日志。然后,功能将在几秒钟后完成。
async onSubmit(event) {
event.preventDefault();
const coverImage = await ipfs.files.add(this.state.buffer, (error, result) =>{
if(error){
console.error(error)
return
}
console.log('Here is: ', result[0].hash)
//Return the hash value
return result[0].hash
})
const contents = await ipfs.files.add(this.state.contentBuffer, (error, result) =>{
if(error){
console.error(error)
return
}
console.log('Here is: ', result[0].hash)
//Return the hash value
return result[0].hash
})
let answer ={thePic: coverImage, theContents: contents}
console.log(answer) //This shows as {thePic: undefined, theContents:
//undefined}
}
我希望在coverImage
和theContents
完成之后获得控制台日志,但是它会立即发生。
答案 0 :(得分:2)
https://github.com/ipfs/interface-ipfs-core/blob/master/SPEC/FILES.md#add
“如果未传递回调,则将返回承诺。”
await
仅在您调用返回诺言的函数时才有意义。
如果您修改代码以在异步调用后继续在异步函数中使用,则返回的值应该是您要查找的结果,并且应以期望的顺序发生。
const imageResult = await ipfs.files.add(this.state.buffer);
const coverImage = imageResult[0].hash;
如果要处理错误情况,请在try / catch中包装整个等待的调用;该错误将是中间诺言的任何错误条件引发的错误。