async-await - 我的异步函数中的等待变量似乎没有逐行执行
问题描述
我有两个等待函数的变量。我只是想在它们完成后对它们进行控制台记录,但是当它跳过时我对它们都没有定义。
在等待功能首先发生之后发生的控制台日志。然后函数在几秒钟后完成。
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
但它会立即发生。
解决方案
https://github.com/ipfs/interface-ipfs-core/blob/master/SPEC/FILES.md#add
“如果没有通过回调,则返回一个承诺。”
await
仅当您调用返回承诺的函数时才有意义。如果您在 async 调用之后修改代码以在 async 函数中继续,则返回的值应该是您正在寻找的结果,并按照您期望的顺序发生。
const imageResult = await ipfs.files.add(this.state.buffer);
const coverImage = imageResult[0].hash;
如果您想处理错误情况,请将整个等待调用的集合包装在 try/catch 中;错误将是任何中间承诺的错误条件引发的错误。
推荐阅读
- typescript - 在简单装饰器中保留方法签名
- algorithm - Cracking The Coding Interview - 打印方程的所有正整数解
- javascript - Firebase 数据提供者 + 自定义数据提供者 - React 管理员
- r - 将已创建的变量分配给 R 中的新变量
- reactjs - 为什么复选框不检查?(反应)
- ios - Trello ios 应用程序深层链接不起作用
- r - 如果在 R 中的数据集的任何行中发生了某些事情,则创建一个虚拟对象
- javascript - 添加 onclick 函数以转到 url 代码
- javascript - 使用多个嵌套对象 Angular 初始化接口的更简单方法
- apache-kafka - kafka 标头,在消费者处